问题描述
|
您好我有一个div如下
<div id=\"test\" class=\"test2\">
<p> <a href=\"\"> <a> </p>
<p> <a href=\"\"> <a> </p>
<p> <a href=\"\"> <a> </p>
<p> <a href=\"\"> <a> </p>
</div>
(我删除了数据,但这就是结构)
如何使用javascript的addChild函数添加新节点
<p> <a href=\"\"> <a> </p>
我知道如何使用removeChild函数,但是我无法使用addChild函数查找文档和示例。
如果我在php数组中有节点字符串,并且可以通过按钮通过GET调用执行包含该数组的php脚本,请单击如何使用addChild函数将节点字符串放入div?
解决方法
addChild
是一个php函数,javascript函数称为appendChild
:
var dv = document.createElement(\"p\");
dv.innerHTML = \"<a href=\"\"> </a> \";
document.getElementById(\'test\').appendChild(dv)
或者,您可以将节点字符串附加到html:
document.getElementById(\'test\').innerHTML += \'<p> <a href=\"\"> <a> </p>
\'
,由于您拥有的是字符串,因此您首先需要为其创建DOM表示形式(您不能将字符串传递给appendChild,而只能将其传递给dom元素)。为此,最简单的方法是将其放在另一个元素中,然后获取其内容。
var temp = document.createElement(\'div\'); // create a temporary dom element
temp.innerHTML = \'<p><a href=\"#\">some cool html string</a></p>\'; // give it your html string as content,the browser will then create the corresponding dom representation
var childs = temp.childNodes; // grab the resulting child elements
document.getElementById(\'where_to_append\').appendChild(childs); // append them to where you want
或者您也可以通过使用innerHTML来简单地将其设置为没有appendChild:
var my_div = document.getElementById(\'where_to_append\');
my_div.innerHTML = my_div.innerHTML + \'<p><a href=\"#\">some cool html string</a></p>\';
,W3Schools提供了使用appendChild()添加节点的示例