代码之家  ›  专栏  ›  技术社区  ›  dennismonsewicz

在两个div中循环元素的jQuery

  •  0
  • dennismonsewicz  · 技术社区  · 14 年前

    我有一个脚本,它循环遍历一个DOM元素列表,并在找到每个元素时对它们进行操作。我遇到的问题是,我需要在两个不同的div中搜索相同的元素。

    这就是我目前所拥有的

    var elements = {
                1 : "h1",
                2 : "h2",
                3 : "h3",
                4 : "h4",
                5 : "p",
                6 : "li",
                7 : "a",
                8 : "td",
                9 : "span",
                10 : "img"
            }
    
            $.each(elements, function(key, val){
                if(val != "img") {
                    if($(".t_content " + val + ":not([id^=element])"))
                        $(".t_content " + val + "[id^=element]").addClass('t_element');
                } else {
                    $('.t_content, .t_component').find('img, div > img').addClass('t_element edit_img_area').removeClass('yellow');
                    $(val).unwrap('a');
                }
            });
    

    我正在搜索的div是 $(".t_content") 但我想找 .t_content .t_component ... 我知道你可以这样搜索 $(".t_content, .t_component") 但我不知道如何把它融入这个剧本。

    谢谢你的帮助!

    3 回复  |  直到 14 年前
        1
  •  1
  •   Brandon Montgomery    14 年前

    你为什么不做这样的事:

    $("h1, h2, h3, h4 ...", $(".t_content, .t_component")).not("[id^=element]").addClass("t_element");
    

    您可以在jQuery中将第二个参数(context)传递给$(),告诉它在上下文中查找选择器中的项。在您的情况下,第二个参数将是要在其中搜索的两个div: $(".t_content, .t_component") .

        2
  •  2
  •   Griff    14 年前

    无需循环,只需一次选择所有元素:

    $('h1, h2, h3,... ').doSomething()
    
        3
  •  1
  •   Oscar Godson    14 年前

    你可以这样做:

    $elements = $('h1,h2,h3,h4,...');
    $elements.whateverHere();
    

    或者,另一种方法是,如果将项目存储在一个简单的数组中,则可以执行以下操作:

    elements = ['h1','h2','h3'];
    for(x in elements){
       if(elements[x] == 'h1'){/*Do something here*/}
    }
    

    在第一个示例中,im saving $elements 为了让它更干燥,因为您可以重用这一块,如果您想在其他地方使用它,它会更快,因为元素现在缓存在jQuery中。

    以下是如何循环使用JSON:

    for (var key in element) {
      if (element.hasOwnProperty(key)) {
        alert(key + " -> " + element[key]);
      }
    }
    

    我把它放在一个数组中,因为它看起来不需要看到键和值,只需要一个,嗯,元素数组来检查。