简体   繁体   English

jQuery-按类选择嵌套元素

[英]JQuery - Selecting nested elements by class

I want to select li elements by class names but it's not working as I want. 我想通过类名选择li元素,但是它不能按我的要求工作。 See the following code: 请参见以下代码:

var HTML = '<div class="product">' +
    '<ul class="listing">' +
    '<li class="item">1</li>' +
    '<li class="item">2</li>' +
    '<li class="item">3</li>' +
    '<li class="item">4</li>' +
    '<li class="item">5</li>' +
    '</ul>' +
    '</div>';


alert($(HTML).find('.product .listing .item').html()); //does not work
alert($(HTML).find('.listing .item').html()); //WORKS!

Why I am not able to select items product class? 为什么我无法选择商品产品类别?

Because .product is one of the selected elements, it's a top level element. 由于.product是所选元素之一,因此它是顶级元素。 .find would try to find the elements with class product inside the .product element. .find将设法找到类元素product 里面 .product元素。

Maybe you are looking for .filter : 也许您正在寻找.filter

Reduce the set of matched elements to those that match the selector or pass the function's test. 将匹配元素的集合减少到与选择器匹配或通过功能测试的元素。

alert($(HTML).filter('.product').find('.listing .item').html());

jQuery find looks for descendents of the current jQuery selection. jQuery find查找当前jQuery选择的后代。 In this case, $(HTML) is already the div with the product class, so .find('.product .listing .item') would look for descendents of the top div with the class of product . 在这种情况下, $(HTML)已经是具有product类的div ,因此.find('.product .listing .item')将查找具有product类的顶级div后代。 In this case, using .find('.listing .item') is correct. 在这种情况下,使用.find('.listing .item')是正确的。

i am not sure if this is something you're looking for? 我不确定这是您要找的东西吗?

var HTML = '<div class="product">' +
    '<ul class="listing">' +
    '<li class="item">1</li>' +
    '<li class="item">2</li>' +
    '<li class="item">3</li>' +
    '<li class="item">4</li>' +
    '<li class="item">5</li>' +
    '</ul>' +
    '</div>';


alert($('.item', HTML));

please see the fiddle http://jsfiddle.net/s1s3zjdL/ 请参阅小提琴http://jsfiddle.net/s1s3zjdL/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM