简体   繁体   English

Javascript:如何使在 function 中创建的元素可点击

[英]Javascript : How to make a element clickable that was created in a function

Hey I have a problem that I don't know how to solved.嘿,我有一个问题,我不知道如何解决。 To make simple.为了简单。 I have a script that create element based on what I have get from a server.我有一个脚本,它根据我从服务器获得的内容创建元素。 At moment I create an image with the id "add" And I want when we click on this image to trigger a function so I did a little script目前,我创建了一个 ID 为“add”的图像,我希望当我们单击此图像时触发 function 所以我做了一个小脚本

 document.getElementById('add').onclick = function(){ alert('ADD;'); // <- For the test }

But I get a problem when Uncaught TypeError: document.getElementById(...) is null .但是当Uncaught TypeError: document.getElementById(...) is null时出现问题。 I thing this because I create this element in the other function and he is not directly in the html code.我之所以这样做,是因为我在另一个 function 中创建了这个元素,而他并不直接在 html 代码中。 But I don't know how to solve that.但我不知道如何解决。

You have to append the element to the document:您必须将 append 元素添加到文档中:

document.appendChild(yourElement); 

Then you have to add an EventListener to your object:然后你必须在你的 object 中添加一个 EventListener:

document.getElementById('add').addEventListener("click", 
function() { 
alert('test'); 
});

i think your example is not long enought to answer you properly but to do want you want, you need to create your element, then attach your event to the element.我认为您的示例不足以正确回答您,但想要您想要,您需要创建您的元素,然后将您的事件附加到该元素。 I'm pretty sure you are trying to set the event on a element that doesn't already exist in DOM我很确定您正在尝试在 DOM 中尚不存在的元素上设置事件

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

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