简体   繁体   English

为什么 jQuery.find() 只返回第一个元素?

[英]why jQuery .find() only return first element?

I am trying to use find() function to get all my children element, with each() function I am expecting it return all element, but it only get first element.我正在尝试使用find() function 来获取我的所有子元素, each() function 我期待它返回所有元素,但它只获得第一个元素。 Is there any misunderstanding with these two functions?这两个功能有什么误解吗?

 if ($('.test').length > 0) { var srcset; $(".test").each(function(index, ele) { srcset = $(ele).find("source").attr("srcset"); console.log(srcset); }); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <picture class="test"> <source srcset="###"> <source srcset="###"> <source srcset="###"> <img src="#" alt=""> </picture>

You are getting the first one because .attr() will return the first element attribute, you have to loop through the selection using .each() , and one more thing you can use ".test source" selector directly, here is a working snippet:你得到第一个是因为.attr()将返回第一个元素属性,你必须使用.each()循环选择,还有一个你可以直接使用".test source"选择器的东西,这是一个工作片段:

 if ($('.test').length > 0) { srcset = $(".test source"); srcset.each(function(i, el){ console.log($(el).attr('srcset')); }); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <picture class="test"> <source srcset="###"> <source srcset="###"> <source srcset="###"> <img src="#" alt=""> </picture>

Actually, .find("source") returns all the elements as you can see here:实际上, .find("source")返回所有元素,如您在此处看到的:

 $(".test").each(function() { var source = $(this).find("source"); console.log(source.length); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <picture class="test"> <source srcset="###"> <source srcset="###"> <source srcset="###"> <img src="#" alt=""> </picture>

You can see source.length returns 3 above, but the issue is with .attr("srcset") .您可以在上面看到source.length返回3 ,但问题在于.attr("srcset") When we use .attr() it only returns the value of the first matched element in the collection.当我们使用.attr()时,它只返回集合中第一个匹配元素的值。 To fix this issue you simply need to loop through all source elements and then get srcset like:要解决此问题,您只需遍历所有source元素,然后获取srcset如下:

 var srcset; $(".test source").each(function() { srcset = $(this).attr("srcset"); console.log(srcset); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <picture class="test"> <source srcset="/abc"> <source srcset="/123"> <source srcset="/example/object/"> <img src="#" alt=""> </picture>

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

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