gpt4 book ai didi

javascript - jQuery attr() 仅适用于第一个元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:48:36 25 4
gpt4 key购买 nike

我不明白为什么 attr() 只被调用一次,

我的html是

<table id="myTable">
<tbody>
<tr>
<td>...</td>
<td>...</td>
<td>
<abbr title='first'>Demo1</abbr>
</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>
<abbr title='second'>Demo2</abbr>
</td>
</tr>
.
.
.
</tbody>
</table>

现在我想得到所有缩写的“标题”,所以写了以下查询

$(document).ready(function () {
console.log($('#myTable tr td:nth-child(3) abbr').attr("title"));
}

所以,它应该返回我

first
second
.
.
.

但输出只是"first",

但是如果写

var oRows = $('#myTable tbody tr');
$.each(oRows, function (i) {
console.log($(this).children('td:nth-child(5)').children().attr("title"));
});

然后我得到正确的输出。但我认为这不是一种正确的方法,所以任何人都可以告诉我哪里出错了。

我还读了this回答了,还是不太清楚

谢谢

最佳答案

.attr() 返回第一个元素的属性。如果您想要所有匹配元素的属性,请使用 map:

var titles = $('#myTable tr td:eq(3) abbr').map(function() {
return $(this).attr('title'); // or just `return this.title`
}).get();

关于javascript - jQuery attr() 仅适用于第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15183876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com