Attach event to dynamic elements in javascript

前端 未结 10 2253
一生所求
一生所求 2020-11-21 23:16

I\'m trying to insert html data dynamically to a list that is dynamically created, but when i try to attach an onclick event for the button that is dynamically created the e

10条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 23:35

    I have found the solution posted by jillykate works, but only if the target element is the most nested. If this is not the case, this can be rectified by iterating over the parents, i.e.

    function on_window_click(event)
    {
        let e = event.target;
    
        while (e !== null)
        {
            // --- Handle clicks here, e.g. ---
            if (e.getAttribute(`data-say_hello`))
            {
                console.log("Hello, world!");
            }
    
            e = e.parentElement;
        }
    }
    
    window.addEventListener("click", on_window_click);
    

    Also note we can handle events by any attribute, or attach our listener at any level. The code above uses a custom attribute and window. I doubt there is any pragmatic difference between the various methods.

提交回复
热议问题