我的页面上有一系列 div,当字符串保存在数组中时,我无法选择包含特定字符串的每个 div。例如,如果数组 = ['foo', 'qux'],我希望能够选择包含 'foo' 的 div 和包含 'qux' 的 div。
<div class="word word1">foo</div>
<div class="word word2">bar</div>
<div class="word word3">baz</div>
<div class="word word4">qux</div>
脚本
array = ['foo', 'qux'];
for (var i = 0; i < array.length; i++) {
array_text = array[i];
alert( $( "div:contains(array_text)" ).text() );
}
我也使用过这个脚本但没有成功:
correct_matches = ['foo', 'qux'];
$.each(correct_matches, function(index, value){
alert( $( "div:contains(value)" ).text() );
}
);
我使用警报只是为了确定 $("div:contains(array_text)") 选择器是否正常工作。选择器是我遇到问题的地方: $( "div:contains('bar')") 按预期工作。使用 array_text 变量后,我会收到带有空字符串的警报。有什么建议么?谢谢。
最佳答案
检查这个 FIDDLE 。
您正在测试 div
中是否包含文本 array_text
。
我不确定这是否是最佳方案,但它确实有效。
jQuery 版本:
$(function () {
var array = ['baz', 'qux'];
for (var i = 0; i < array.length; i++) {
array_text = array[i];
$('div').each(function () {
if ($(this).text() == array_text) {
alert(array[i]);
// do more stuff with $(this) (which is the div)
}
});
}
});
关于javascript - jQuery/Javascript : iterate over an array to select divs from the array values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23961653/