[英]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.我仍在学习 JS 和 JQuery,并且遇到了 on click 事件未触发的问题。 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:在 Jquery 部分,我有:
$(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.其中 #Menu_HW_Main 是包含菜单的 div 的 id。 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.当我在 DOM 中创建标题/菜单时,事件触发得很好。 But when I create it through JS, it does not fire.但是当我通过 JS 创建它时,它不会触发。 What am I missing?我错过了什么?
Your code seems fine but instead of mixing vanilla JS
you may use only jQuery
to create the h1
:您的代码看起来不错,但您可以只使用jQuery
来创建h1
而不是混合 vanilla JS
:
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:如果"#Menu_HW_Main"
也是一个动态(由js
创建)元素,那么试试这个:
$(document).on('click', '.SelectableMenu', function () {
alert("Test");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.