Javascript Can';t向DOM元素添加onclick事件
我在一个div中创建了一个p元素(我们称之为“test div”),我想在它上面添加onclick事件,我可以给它一个类和一个id,但在添加onclick时会出错。它说它有类型void。我的代码基本上是这样的:Javascript Can';t向DOM元素添加onclick事件,javascript,html,dom,Javascript,Html,Dom,我在一个div中创建了一个p元素(我们称之为“test div”),我想在它上面添加onclick事件,我可以给它一个类和一个id,但在添加onclick时会出错。它说它有类型void。我的代码基本上是这样的: var son = document.createElement("p"); var node = document.createTextNode("test"); son.appendChild(node); var father = document.getElementById("
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
回答:son.addEventListener(“单击”,function(){sonFunction(randomVar)}) 您正试图更改
onclick
属性,该属性需要一个字符串,并将没有返回值的sonFunction
的返回值赋给它,因此(void
)
可以使用以下字符串设置onclick
属性:
son.onclick = 'sonFunction(randomVar);';
这样做将为您提供类似以下内容的HTML输出:
<p class="son-class" onclick="sonFunction(randomVar);">
...
</p>
或
使用以下命令:son.onclick='sonFunction(randomVar);';这是错误的,这实际上是我第一次尝试的,我在stackoverflow上搜索,而你实际上没有把它放在一个字符串中。在执行son.addEventListener('click',sonFunction(randomVar))时;对于son.addEventListener('click',function(randomVar){}),我也得到了同样的错误;
function sonFunction() {
// something here
};
son.addEventListener('click', sonFunction);
son.addEventListener('click', function () {
// something here
});