javascript - appendChild() 不接受传递的字符串参数作为参数?

标签 javascript jquery html

我的代码是为了添加另一段<p>hello</p>单击“新建”按钮后,在现有的 2 个下。

错误一定是在传递来自onclick 的值时发生的函数或 createTextNodeappendChild() (不是在函数等中正确使用的正确数据类型)。我知道这一点是因为函数本身可以正常工作而无需将参数传递给 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 的程序。 .显然,我打算利用 appendChildremoveChild ,如果您知道更合适的方法来指导我,将不胜感激。

最佳答案

你没有正确解析

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/

相关文章:

javascript - 如何从谷歌地理编码解析 json (jquery)?

javascript - 如何在 Angular 单元测试中使 Material 组件与 Karma 一起工作

javascript - 卡住了多次点击事件

javascript - 更改类后单击()

javascript - 如何使用 Angular 防止随机定位的图像重叠

JAVASCRIPT:具有自动生成的选定值组合的动态表行

html - 使父 div 扩展到窗口之外以包裹所有子项

javascript - 使用 TypeScript 和 Express, View 不会呈现。相反,显示服务器文件

javascript - 将 react native 侧菜单添加到我的应用程序(来自 react native 元素) - 应用程序在启动时崩溃

javascript - 如何调用从ajax新添加的函数