我的代码是为了添加另一段<p>hello</p>
单击“新建”按钮后,在现有的 2 个下。
错误一定是在传递来自onclick
的值时发生的函数或 createTextNode
或 appendChild()
(不是在函数等中正确使用的正确数据类型)。我知道这一点是因为函数本身可以正常工作而无需将参数传递给 createTextNode()
只需键入一个字符串即可。
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
function saveSelection(selection) {
var para = document.createElement("p3");
var node = document.createTextNode(selection);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
</script>
<button type="button" onclick="saveSelection("hello")">New</button>
旁注:如果您好奇,更广泛的目标是最终编写一个类似于 this 的程序。 .显然,我打算利用 appendChild
和 removeChild
,如果您知道更合适的方法来指导我,将不胜感激。
最佳答案
你没有正确解析
onclick="saveSelection("hello")"
应该是
onclick="saveSelection('hello')"
然后在这里
var para = document.createElement("p3");
元素应该是 p
而不是 p3
看下面的演示
function saveSelection(selection) {
var para = document.createElement("p");
var node = document.createTextNode(selection);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<button type="button" onclick="saveSelection('hello')">New</button>
关于javascript - appendChild() 不接受传递的字符串参数作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50883575/