简体   繁体   English

如何在纯JS中为动态创建的元素定义事件?

[英]How to define events for dynamically created element in pure JS?

How to catch elements onclick event when element may be created in future or added dynamically? 当元素可能在将来创建或动态添加时,如何捕获元素onclick事件?

// Here i need to define function for click
// In jQuery it would be like this: jQuery('body').on('click', 'a.some-link-class', function(){});

var some_link = document.createElement('a');
    some_link.class = 'some-link-class';
    some_link.href = '#';

var some_link_text = document.createTextNode('Some Link Title');
    some_link.appendChild(some_link_text);

document.body.appendChild(some_link);

You must use event delegation for JS. 您必须将事件委托用于JS。 just attach an event to a parent item or document and check in the parent if trigger is your element. 只需将事件附加到父项或文档,然后检查父项是否是触发器。 You can use a class name or tag name etc. 您可以使用类名或标签名等。

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click",function(e) {
    // e.target is the clicked element!
    // If it was a list item
    if(e.target && e.target.nodeName == "LI") {
        // List item found!  Output the ID!
        console.log("List item ",e.target.id.replace("post-")," was clicked!");
    }
});

in this way the event also works for elements what will be added afterwards. 这样,事件也适用于随后添加的元素。

You can attach an event to the body and test if the source of the event is the control type you want, or a class, or something else. 您可以将事件附加到主体上,并测试事件的源是否是所需的控件类型,类或其他类型。

//attach the event to everything in the body
document.body.addEventListener('click', eventFunction, false);

//event function
function eventFunction(e)
{
   //test if the source triggering the event is an element from the class you want
   //you can do the test on the class, tagname... anything you desire
   if(e.ClassName.match('myclass'))
   {
      //do something if the class matches
      dosomething();
   }
}

With this, you can create any element you want after that. 这样,您可以在此之后创建所需的任何元素。 If they have the good class they will trigger the event if clicked and the function will run. 如果它们具有良好的类,则单击它们将触发事件,然后函数将运行。

Just attach it when you create it: 只需在创建它时附加它:

some_link.onclick = function() {
    //do stuff
}

Either

some_link.addEventListener('click', handler);

or 要么

some_link.onclick = handler;

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

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