我错误地试图找到元素的img src属性。这是我的代码,我将解释预期的行为。
$('.flex-control-nav').ready(function(){
$('.flex-control-nav').find('li').each(function(){
console.log($('img').attr('src'));
});
});
html就像这样:
<ol class="flex-control-nav flex-control-thumbs">
<li><img src="//example.com/s/files/1/0519/6401/products/c7b83f87-4c30-4d47-a32b-3a4e7e645607_400x400.jpg?v=1546474879" class="flex-active" draggable="false"></li>
<li><img src="//example.com/s/files/1/0519/6401/products/blahblah_400x400.jpg?v=1546643593" draggable="false"></li>
<li><img src="//example.com/s/files/1/0519/6401/products/blahblah2-Hat_400x400.jpg?v=1546643586" draggable="false"></li>
</ol>
通过在flex-control-nav中找到li,我希望它能在console.log中找到该li中的每个img,但是它将记录最初找到的每个img。获取每个li的img src属性的正确方法是什么?
答案 0 :(得分:2)
jQuery不会自动将选择器的作用域限定为.each()
中的当前元素,您需要自己进行。 this
包含迭代的当前元素。
$(document).ready(function() {
$('.flex-control-nav').find('li').each(function() {
console.log($(this).find('img').attr('src'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol class="flex-control-nav flex-control-thumbs">
<li><img src="//example.com/s/files/1/0519/6401/products/c7b83f87-4c30-4d47-a32b-3a4e7e645607_400x400.jpg?v=1546474879" class="flex-active" draggable="false"></li>
<li><img src="//example.com/s/files/1/0519/6401/products/blahblah_400x400.jpg?v=1546643593" draggable="false"></li>
<li><img src="//example.com/s/files/1/0519/6401/products/blahblah2-Hat_400x400.jpg?v=1546643586" draggable="false"></li>
</ol>
答案 1 :(得分:1)
要在有限范围内搜索,请选择该范围并使用find()
:
$(document).ready(function() {
$('.flex-control-nav').find('li').each(function() {
console.log($(this).find('img').attr('src'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol class="flex-control-nav flex-control-thumbs">
<li><img src="//example.com/s/files/1/0519/6401/products/c7b83f87-4c30-4d47-a32b-3a4e7e645607_400x400.jpg?v=1546474879" class="flex-active" draggable="false"></li>
<li><img src="//example.com/s/files/1/0519/6401/products/blahblah_400x400.jpg?v=1546643593" draggable="false"></li>
<li><img src="//example.com/s/files/1/0519/6401/products/blahblah2-Hat_400x400.jpg?v=1546643586" draggable="false"></li>
</ol>
答案 2 :(得分:0)
您不会在每个循环中将当前元素传递给匿名函数:
$('.flex-control-nav').find('li').each(function(index, element){
console.log($('img', element).attr('src'));
});