2015-10-05 70 views
0

小提琴:http://jsfiddle.net/0dapo32a/1/如何使用XML标签的DIV中的jQuery选择

HTML:

<div class="test1"> 
<office1><a title="98 Tuvalu road" href="/IDD=1603">98 Tuvalu road</a></office1> 
</div> 
<div class="test1"> 
<office2><a title="900 Bleek Ave" href="/IDD=23">900 Bleek Ave</a></office2> 
</div> 
<div class="test1"> 
<office3><a title="73 Wabash Street" href="/IDD=3">73 Wabash Street</a></office3> 
</div> 

如何编辑JQuery的追加基于标准的锚文本。

回答

2

你的选择是通过使用>寻找的.test1直接孩子。

更改为

$(".test1 a");//match any `a` that is descendant of class `test1` 

,它工作正常

DEMO

+0

愚蠢的我。我忘了为类选择器包含'.':/ – Si8

0

jQuery并不在乎标签是XML还是其他任何东西,因为它根据字符串查找它。

所以你可以使用:

$("div office1").css("backgroundColor","red"); 

//or 
$("div office1").append('<a href="http://google.com">google</a>'); 
1

您使用其它标签名

$(".test1 office1 a") 

如果你想针对所有3级办事处的标签,你需要做三次用同样的方法并用逗号分隔它们

$(".test1 office1 a,.test1 office2 a,.test1 office3 a") 

或者只是删除您正在使用的子选择器

$(".test1 a") 

虽然注意到最后一个将选择任何a标签是内.test1

1

jQuery选择与>将查找.test1类的直接孩子。将其更改为$(".test1 a")匹配所有a是后裔那类:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div class="test1"> 
 
<office1><a title="98 Tuvalu road" href="/IDD=1603">98 Tuvalu road</a></office1> 
 
</div> 
 
<div class="test1"> 
 
<office2><a title="900 Bleek Ave" href="/IDD=23">900 Bleek Ave</a></office2> 
 
</div> 
 
<div class="test1"> 
 
<office3><a title="73 Wabash Street" href="/IDD=3">73 Wabash Street</a></office3> 
 
</div> 
 
<script> 
 
var vCityState = new Array("| Darien CT", "| Greenwich CT"); 
 

 
$(".test1 a").text(function (index, oldText) { 
 
    if (oldText.indexOf("900") > -1) { 
 
\t \t \t \t \t return oldText + vCityState[0]; 
 
\t \t \t \t } 
 
    if (oldText.indexOf("Wabash") > -1) { 
 
\t \t \t \t \t return oldText + vCityState[1]; 
 
\t \t \t \t } 
 
}); 
 
</script>