I am trying to load my navigation bar like this:
$.get("nav.html",function(menuData){
$("body").html(menuData);
)};
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);
});
});
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.
EDIT
this was one answer that worked:
use
$("body").on('click','#menu-item-1',function(){
etc.
});
because menu-item-1 wasn’t created yet when we tried
$("#menu-item-1).mousedown
To give you an answer replacing
with
works because when the
.on()is delegated#menu-item-1isn’t on the page yet, but when it is called it can select#menu-item-1