javascript - jQuery/Javascript : iterate over an array to select divs from the array values

标签 javascript jquery arrays

我的页面上有一系列 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/

相关文章:

javascript - 拦截任何请求 - javascript

javascript - 使用 setInterval 函数定位 div

php - 如何在 Symfony 1.4 的成功页面中获取数据数组

javascript - 带有基于浏览器的 API 的 node.js

javascript - 中继操作名称是什么?

javascript - 如何在javascript中获取正方形边缘附近的随机点

jquery - 在 jQuery 中,给定一个选择菜单元素,如何访问第一个选项元素?

javascript - Google map API v3 显示行程时间

c++ - 用空白填充二维数组(从文件输入)

javascript - 删除字符串数组中的空格 (JavaScript)