Applying an onclick event to an element that doesn't exist on page load

孤街醉人 提交于 2019-12-05 13:12:44

you need to delegate your elements to static parent , if the element is added dynamically using on() try this

  $(document).on('click','li a',function(e){
    e.preventDefault();
    var rel = this.rel;
     //or using attr()
    var rel=$(this).attr('rel'); 
     alert(rel);  
  });

however delegating it to its closest static parent(present at a time of insertion) is better than document itself.. so if you are adding the list inside main_category_field div.. then you can use

    $('#main_category_field').on('click','li a',function(e){     
         //same stuff

The key word is event delegation. If you want to assign event handlers to dynamically added elements for which you know their "future" selectors, you should use the .on() method on an (already existing) parent element of those dynamic elements.

The second parameter to .on() is then the selector of the dynamically added elements

$(document).on('click', '.cat_list li a', function(e) {
   alert(this.rel);   // show the "rel" attribute of the clicked a element
   e.preventDefault();  // to prevent the default action of anchor elements
});

Use .on for listen dynamically created dom elements as follows

$(document).on('click','div.cat_list ul li a',function(){
     var rel=$(this).attr('rel');//to get value of rel attribute
     alert(rel);   
     //other operations
});

To bind an event handler to an element that does not yet exist on the page use on.

$(document).on("click", "#main_category_field", function(e){
   e.preventDefault();
   var rel = e.target.rel;
});

JS Fiddle: http://jsfiddle.net/82bAb/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!