Jquery 为什么。第一个()赢了';你不在这里工作吗?
在下面的代码中,我试图获取“latest”下第一个div的值,但我一直得到“undefined”。我期望值是5705。这应该有用的,对吧?我该如何纠正这一点Jquery 为什么。第一个()赢了';你不在这里工作吗?,jquery,Jquery,在下面的代码中,我试图获取“latest”下第一个div的值,但我一直得到“undefined”。我期望值是5705。这应该有用的,对吧?我该如何纠正这一点 var auto_refresh = setInterval(function() { console.log($('.latest').first().attr('lastValue')); }, 5000); // refresh every 5 seconds html部分:这里将添加更多div。所以5705可能是5710或
var auto_refresh = setInterval(function()
{
console.log($('.latest').first().attr('lastValue'));
}, 5000); // refresh every 5 seconds
html部分:这里将添加更多div。所以5705可能是5710或其他东西
<div class="latest">
<div class="story" lastValue="5705">Story 5</div>
<div class="story" lastValue="5704">Story 4</div>
<div class="story" lastValue="5703">Story 3</div>
<div class="story" lastValue="5702">Story 2</div>
<div class="story" lastValue="5701">Story 1</div>
</div>
故事5
故事4
故事3
故事2
故事1
您想选择第一个子元素,而不是第一个类为latest的元素
console.log($('.latest > div').first().attr('lastValue'));
您必须选择第一个子容器,而不是第一个容器
$('.latest>div').first().attr('lastValue')
或
因为您选择了错误的元素,所以您需要
.story
元素,但您选择的是.latest
元素。使用:
$('.latest .story:first').attr('lastValue');
或:
或:
有几种方法可以做到这一点:
console.log($('.latest .story').first().attr('lastValue'));
或
或
$('.latest')
返回在class
属性中具有latest
的任何元素的数组。
因此
$('.latest').first()返回此数组的第一个元素。
在您的示例中,返回的HTML元素div.latest
不是第一个div.story
如果您尝试:console.log($('.latest').first().attr('class'))
您将看到您编写的内容与之匹配
似乎您想要访问第一个最新的故事,表示div.latest
元素下的第一个div.story
元素。
所以试试:console.log($('.latest.story').first())
我对JSFIDLE的测试如下:
$('.latest .story:first-child`).attr('lastValue');
$('.story:first-child').attr('lastValue');
console.log($('.latest .story').first().attr('lastValue'));
console.log($('.latest .story:first-child').attr('lastValue'));
console.log($('.latest').find('.story').attr('lastValue'));