且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用纯javascript获取li元素onclick,而不会将onClick应用到每个元素

更新时间:2023-12-05 13:03:52

You could add an event listener to the parent ul and then use e.target.id to get the id of the clicked element. Just check to make sure that the clicked element is actually an li since it's possible you may not be clicking on one.

Example Here

var ul = document.getElementById('bulk');  // Parent

ul.addEventListener('click', function(e) {
    if (e.target.tagName === 'LI'){
      alert(e.target.id);  // Check if the element is a LI
    }
});


As pointed out in the comments, this approach won't work when the child of an li is clicked. To solve this, you would need to check to see if the parent element of the clicked element is the one that the click event is attached to.

Example Here

var ul = document.getElementById('bulk'); // Parent

ul.addEventListener('click', function (e) {
    var target = e.target; // Clicked element
    while (target && target.parentNode !== ul) {
        target = target.parentNode; // If the clicked element isn't a direct child
        if(!target) { return; } // If element doesn't exist
    }
    if (target.tagName === 'LI'){
        alert(target.id); // Check if the element is a LI
    }
});

相关阅读

推荐文章