gpt4 book ai didi

jquery - appendTo 在 jQuery 代码中不起作用?

转载 作者:太空宇宙 更新时间:2023-11-03 21:59:26 25 4
gpt4 key购买 nike

我正在尝试使用 id 选择器将段落添加到 h2 标签。但是,由于某种原因,它无法正常工作。有人可以帮我解决这个问题吗?

我有一把 fiddle 来试一试。请参阅:http://jsfiddle.net/ahLqZ/4/

下面是我的代码:

 $(document).ready(function(){

$("#cevre h2").appendTo($(this).next("p"));

})​

最佳答案

试试这个:

$("#cevre h2").each(function() {
$(this).appendTo($(this).next("p"));
});

使用 .each() 遍历 h2元素 - 然后 $(this)变成每个h2元素而不是那个 document元素

Working example here

注意 使用 appendTo在一个已经存在的 DOM 元素上移动它......你可能想要的(也许不是)是这样的:

$("#cevre h2").each(function() {
$(this).clone().insertAfter($(this).next("p"));
});

使用 .clone() 创建 h2 的克隆首先和 .insertAfter() <p> 之后插入新克隆的 DOM 元素元素而不是在其中...

Working example here

另一个注意事项 - 具有重复的无效 HTML id单个页面中的属性...我建议您更改<div id="cevre"><div class="cevre"> ...然后您的 jQuery 选择器变为 $(".cevre h2")

另一个注意事项 - 如果多次使用 jQuery 对象,您应该缓存它们:

$(".cevre h2").each(function() {
var $this = $(this);
$this.clone().insertAfter($this.next("p"));
});

关于jquery - appendTo 在 jQuery 代码中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11525708/

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