无法将onclick事件添加到DOM元素

问题描述 投票:0回答:1

我正在div中创建ap元素(我们称其为“ test-div”),我想在其上添加onclick事件,我可以给它提供一个类和一个id,但是在添加onclick时出现错误。它说它的类型是void。我的代码基本上是这样的:

var son = document.createElement("p");
var node = document.createTextNode("test");
son.appendChild(node);
var father = document.getElementById("test-div");
father.appendChild(son);
son.className = "son-class";
son.id="son-id";
son.onclick= sonFunction(randomVar); //Type 'void' is not assignable error
javascript html dom
1个回答
0
投票

您正在尝试更改需要字符串的onclick属性,并为其分配没有返回值的sonFunction的返回值,因此(void)。

您可以使用诸如以下的字符串设置onclick属性:

son.onclick = 'sonFunction(randomVar);';

这样做将为您提供类似于以下内容的HTML输出:

<p class="son-class" onclick="sonFunction(randomVar);">
    ...
</p>

但是,您可能想为其分配一个事件侦听器,单击该事件侦听器将触发该事件。执行以下操作不会在HTML中添加onclick属性,但会将侦听器保留在Javascript编译器中。这样做通常被称为“不打扰”的Javascript,因为Javascript代码未嵌入HTML中。

function sonFunction() {
    // something here
};
son.addEventListener('click', sonFunction);

son.addEventListener('click', function () {
    // something here
});
© www.soinside.com 2019 - 2024. All rights reserved.