简体   繁体   English

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

[英]Can't add onclick event to DOM element

I'm creating ap element inside a div (lets call it "test-div") and i want to add onclick events on it, i can give it a class and an id but I'm getting errors when adding an onclick.我在 div 中创建 ap 元素(我们称之为“test-div”),我想在其上添加 onclick 事件,我可以给它一个 class 和一个 id,但是添加 ZC0BB219646024E8ADD93 时出现错误。 It says it has type void.它说它有 void 类型。 My code is basically this:我的代码基本上是这样的:

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

Answer: son.addEventListener("click", function(){sonFunction(randomVar)});答案:son.addEventListener("click", function(){sonFunction(randomVar)});

You're attempting to change the onclick attribute, which is expecting a string, and assigning it the return value of your sonFunction which has no return value, hence ( void ).您正在尝试更改onclick属性,该属性需要一个字符串,并为其分配没有返回值的sonFunction的返回值,因此( void )。

You can set the onclick attribute with a string such as:您可以使用以下字符串设置onclick属性:

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

Doing so will give you HTML output similar to:这样做会给你 HTML output 类似于:

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

However, you probably want to assign it an event listener, which will fire the event when clicked.但是,您可能希望为其分配一个事件侦听器,该侦听器将在单击时触发该事件。 Doing the below will not add an onclick attribute to the HTML, but keep the listener in the Javascript compiler.执行以下操作不会将onclick属性添加到 HTML,但会将侦听器保留在 Javascript 编译器中。 Doing this is often called "unobtrusive" Javascript since the Javascript code is not embedded in the HTML.这样做通常被称为“不引人注目的”Javascript,因为 Javascript 代码未嵌入在 HTML 中。

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

Or或者

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

Actually you can use the onclick attribute, just assign it with the setAttribute like this:实际上你可以使用 onclick 属性,只需像这样分配setAttribute

 var son = document.createElement("p"); var node = document.createTextNode("test"); son.appendChild(node); son.className = "son-class"; son.id="son-id"; son.setAttribute('onclick', 'sonFunction()'); var father = document.getElementById("test-div"); father.appendChild(son); function sonFunction() { alert(event.srcElement.id); }
 <div id="test-div">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM