mousedown在动态加载的元素上不起作用 [英] mousedown not working on dynamically loaded element
问题描述
我正在尝试像这样加载导航栏:
I am trying to load my navigation bar like this:
$.get("nav.html",function(menuData){
$("body").html(menuData);
)};
在 nav.html中,我们有类似的东西
and within "nav.html" we have something like
<td id='menu-item-1'>menu item 1</td>
<td id='menu-item-2'>menu item 2</td>
等。因此,我想为每个项目分配一个事件,并尝试了以下操作:
etc. So then I want to assign an event to each item and I have tried this:
$("#menu-item-1").mousedown(function(response){
//create an empty table
$("body").append("table id='menu-item-1-sub-table'></table>");
//retrieve php data and insert it in the table
$.get("data.php",function(response){
$("#menu-item-1-sub-table").html(response);
});
});
问题是事件不会触发。当我直接在javascript中使用html时,它起作用了,例如:
The problem is the event will not fire. It worked when I had the html directly in the javascript, e.g.:
$("body").append("<table><tr><td id='menu-item-1'>menu-item-1</td></tr></table>");
但将其移至另一个文件后将不再起作用。
but upon moving it to another file it no longer works.
编辑
这是一个有效的答案:
使用
$("body").on('click','#menu-item-1',function(){
etc.
});
因为我们尝试时还没有创建menu-item-1
because menu-item-1 wasn't created yet when we tried
$("#menu-item-1).mousedown
推荐答案
为您提供替换
$("#menu-item-1").on("click",function(){
//stuff
});
与
$('body').on('click','#menu-item-1', function(){
//stuff
});
之所以有效,是因为当授权 .on()
#menu-item-1
时,尚未在页面上显示,但调用它时可以选择#menu-item-1
works because when the .on()
is delegated #menu-item-1
isn't on the page yet, but when it is called it can select #menu-item-1
这篇关于mousedown在动态加载的元素上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!