简体   繁体   中英

JQuery On Click Event not firing with JS created elements

I am still learning JS and JQuery and am running into an issue with the on click event not firing. I have created a menu with titles that should be clickable.

            var title = document.createElement('h1');
            title.textContent = "HW Tools";
            title.className += "SelectableMenu";
            hwSection.appendChild(title);

In the Jquery portion, I have:

    $(document).ready(function () {
        $("#Menu_HW_Main").on('click', '.SelectableMenu', function () {
            alert("Test");
        })

where #Menu_HW_Main is the id for the div containing the menu. However, when I click on the title, the alert does not show.

When I create the title/menu in the DOM, the event fires fine. But when I create it through JS, it does not fire. What am I missing?

Your code seems fine but instead of mixing vanilla JS you may use only jQuery to create the h1 :

var h1 = $('<h1/>', {'text':'HW Tools', 'class':'SelectableMenu'});

$("#Menu_HW_Main").append(h1);

If "#Menu_HW_Main" is also a dynamic (created by js ) element then try this:

$(document).on('click', '.SelectableMenu', function () {
    alert("Test");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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