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

Javascript 是否可以在使用jquery将元素插入DOM之前对其进行操作?,javascript,jquery,dom,Javascript,Jquery,Dom,我知道已经有人问过这个问题,但从未真正详细阐述过。我想在页面中的DOM中插入一个元素,但只有在用DOM构建它之后。我知道这是可能的,但这项功能似乎只是部分起作用。例如 // this doesnt work var theDiv = '<div></div>'; $(theDiv).append('<p>test</p>'); alert($(theDiv).html()); // this works var theDiv = '<div

我知道已经有人问过这个问题,但从未真正详细阐述过。我想在页面中的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());
//这不起作用
var theDiv=“”;
$(theDiv).追加(“test

”); 警报($(theDiv.html()); //这很有效 var theDiv=“”; 警报($(theDiv.html());
我希望有人能对这个问题有所了解。

试试这个:

var theDiv = $('<div/>');
theDiv.append('<p>test</p>');
alert(theDiv.html());
var theDiv=$('');
附加(“测试”

); 警报(theDiv.html());
试试这个:

var theDiv = $('<div/>');
theDiv.append('<p>test</p>');
alert(theDiv.html());
var theDiv=$('');
附加(“测试”

); 警报(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
var theDiv='';
$(theDiv).追加(“test

”)//创建一个新的jquery对象并附加一个p 警报($(theDiv.html())//创建一个只包含一个div的新jquery对象并输出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
var theDiv='';
var$d=$(theDiv).append(“test

”)//创建一个新的jQuery对象,然后追加 //p并将其存储在变量中 警报($d.html())//输出变量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
var theDiv='';
$(theDiv).追加(“test

”)//创建一个新的jquery对象并附加一个p 警报($(theDiv.html())//创建一个只包含一个div的新jquery对象并输出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
var theDiv='';
var$d=$(theDiv).append(“test

”)//创建一个新的jQuery对象,然后追加 //p并将其存储在变量中 警报($d.html())//输出变量html的内容

继续编写示例。

我不是一个喜欢jquery的人,但是,框架不是为你创建了结束标记吗?@Mark:我以为jquery会创建结束标记。。。编辑@斯蒂芬,我以为这样可以。。。但是@Mark认为它不。。。这两项工作我猜都看到了这里的讨论:对于我在这个re上的思想模式的“某些”来源:“使用节点而不是Karl re中的字符串:”插入格式良好的xhtml“。我更喜欢这个解决方案,而不是创建变量,而且它在我的测试中确实有效。还要注意的是,在IE xhtml文档中,空元素或自动关闭元素并不总是起作用。我不是一个喜欢jquery的人,但是,框架不是为你创建了结束标记吗?@Mark:我以为jquery会创建结束标记。。。编辑@斯蒂芬,我以为这样可以。。。但是@Mark认为它不。。。这两项工作我猜都看到了这里的讨论:对于我在这个re上的思想模式的“某些”来源:“使用节点而不是Karl re中的字符串:”插入格式良好的xhtml“。我更喜欢这个解决方案,而不是创建变量,而且它在我的测试中确实有效。但也要注意,空的或自动关闭的元素并不总是在IE xhtml文档中工作。