<div class="append-something first"></div>
<div class="append-something second"></div>
<div class="append-something third"></div>
$("#trigger").click(function() {
$(".append-something").append("Some Stuff");
});
你好, 我希望上面的代码将单词“Some Stuff”粘贴/append 到 div 类“append-something”中,但仅粘贴到具有类名的第一个 div 中。 (在我的代码中,单词应该 append 到“第一”,而不是“第二”或“第三”)。非常感谢!
最佳答案
您可以使用:first
或:first-child
选择器。只有最后一个你应该使用 :last
选择器。
对于任何其他元素,您可以使用该元素的索引。 jQuery 将使用 append-something
类创建他找到的所有元素的数组。所以第一个元素将是 0
的索引。
$("#trigger-first").click(function() {
// ":first" and ":first-child" will work.
$(".append-something:first").append("Some Stuff");
});
$("#trigger-last").click(function() {
// ":last" for last option.
$(".append-something:last").append("Some Stuff");
});
$("#trigger-second").click(function() {
// It will return an array of item so you can request on index.
$($(".append-something")[1]).append("Some Stuff");
});
关于jQuery .append() 仅在第一个元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44329642/