문제

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

$("#menu-item-1").on("click",function(){
  //stuff
});

with

$('body').on('click','#menu-item-1', function(){
  //stuff
}); 

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

다른 팁

I think the problem is because you must set your handlers inside the get callback after body.html(menuData). But if it all will work, i think it is a weird way to load menu template on page.

you said another file - did you add jquery to that code ? or maybe element doesnt exist when you load mousedown code - try jquery on-function.

 $('#menuitem').on(function(){

    $("#menu-item-1").mousedown(function(response){
      $("body").append("table id='menu-item-1-sub-table'></table>");
       $.get("data.php",function(response){
       $("#menu-item-1-sub-table").html(response);
       })
     });
   })

your better off appending the table when you get the response rather than appending a table and then setting the html of the appended table

$('body').on('click','#menu-item-1', function() {
  $.get("data.php",function(response){
    $("body").append('<table id="menu-item-1-sub-table">'+response+'</table>');
  });
});

based upon what you've already done

$('body').on('click','#menu-item-1', function() {
  $("body").append("<table id='menu-item-1-sub-table'></table>");
  $.get("data.php",function(response){
    $("#menu-item-1-sub-table").html(response);
  });
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top