Javascript appendChild()不接受传递的字符串参数作为参数?
“我的代码”是指在单击“新建”按钮后,在现有的两个段落下添加另一个段落 错误必须出现在将值从Javascript appendChild()不接受传递的字符串参数作为参数?,javascript,jquery,html,Javascript,Jquery,Html,“我的代码”是指在单击“新建”按钮后,在现有的两个段落下添加另一个段落 错误必须出现在将值从onclick传递到函数或createTextNode或appendChild()(不是函数中正确使用的正确数据类型等)时。我知道这一点,因为函数本身工作正常,无需将参数传递给createTextNode(),只需键入字符串即可 <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p
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>
这是一个段落
这是另一段
函数保存选择(选择){
var para=document.createElement(“p3”);
var节点=document.createTextNode(选择);
子节点(节点)段;
var元素=document.getElementById(“div1”);
要素.附件(第6段);
}
新的
旁注:如果你好奇,更广泛的目标是最终编写一个类似的程序。显然,我计划利用
appendChild
和removeChild
,如果您知道更合适的方法,我将不胜感激。您在传递值时在代码中犯了非常简单的错误
使用单引号(“”)代替双引号(“”)
使用'hello'
代替“hello”
简单 注意双引号。将“hello”改为单引号
<button type="button" onclick="saveSelection('hello')">New</button>
新建
应该是
document.createElement("p");
及
应该是
"saveSelection('hello')"
onclick="saveSelection('hello')"
您没有正确解析
onclick="saveSelection("hello")"
应该是
"saveSelection('hello')"
onclick="saveSelection('hello')"
然后在这里
var para = document.createElement("p3");
元素应该是p
而不是p3
请参见下面的演示
函数保存选择(选择){
var para=document.createElement(“p”);
var节点=document.createTextNode(选择);
子节点(节点)段;
var元素=document.getElementById(“div1”);
要素.附件(第6段);
}
这是一个段落
这是另一段
New
采用您希望创建的标记的名称,而不是其id
。所以,你应该通过“p”,而不是“p3”。您可以稍后使用设置id。