gpt4 book ai didi

javascript - 是否可以在使用 jquery 将元素插入 DOM 之前对其进行操作?

转载 作者:行者123 更新时间:2023-11-28 14:00:46 26 4
gpt4 key购买 nike

我知道已经有人问过这个问题,但从未真正详细说明过。我想将一个元素插入到我的页面的 DOM 中,但只有在使用 DOM 构建它之后才可以。我知道这是可能的,但似乎此功能仅部分有效。例如...

// this doesnt work
var theDiv = '<div></div>';
$(theDiv).append('<p>test</p>');
alert($(theDiv).html());

// this works
var theDiv = '<div></div>';
alert($(theDiv).html());

我希望有人能够阐明这个问题。

最佳答案

这不能按预期工作的原因是因为您每次都创建一个新的 jQuery 对象。

var theDiv = '<div></div>';
$(theDiv).append('<p>test</p>'); //Create a new jquery object and append a p
alert($(theDiv).html()); //create a new jquery object of just a div and output the html

如果你想解决这个问题,你只需要创建一个新变量来保存你的 jQuery 对象。

var theDiv = '<div></div>';
var $d = $(theDiv).append('<p>test</p>'); //create a new jQuery object and than append
//a p and store it in a variable
alert($d.html()); //output the contents of the variable's html

jsfiddle 上的代码示例.

关于javascript - 是否可以在使用 jquery 将元素插入 DOM 之前对其进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5297009/

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