jQuery - cannot bind events to dynamic elements?

后端 未结 6 570
借酒劲吻你
借酒劲吻你 2021-01-13 07:58

I\'ve come to maintain a piece of javascript that downloads some JSON data from the server, builds a new table row (like $(\') and inserts i

相关标签:
6条回答
  • 2021-01-13 08:01

    Try this:

    var a = $('<a class="foo" href="#">ASD</a>');
    $("body").html(a);
    a.click(function() {
        alert('a');
        return false;
    });
    
    0 讨论(0)
  • 2021-01-13 08:07

    You can use event delegation like so.

    $('body').on('click','.foo',function(){
        alert('foo');
    });
    

    This will allow you to set the event handler before the element is present.

    0 讨论(0)
  • 2021-01-13 08:13

    EDITED

    The .on() should be set up like this to work with dynamically created elements. Also, make sure to use Jquery version 1.8 (newest release)

    Also, you need to prevent the standard action of the click if you don't want to scroll to the top.

    Here is a working FIDDLE

    var a = $('<a class="foo" href="#">ASD</a>');
    
    a.appendTo($("body"));
    
    $('body').on('click', 'a', function(e) {
        e.preventDefault();
        $(this).after('<br/><a class="foo" href="#">ASD</a>');
    });
    
    0 讨论(0)
  • 2021-01-13 08:15
    You have various options. You can bind to the element or to the document. 
    

    BIND TO DOCUMENT:

     $(document).on("click", "a.foo", function(event){
    //do stuff here 
     });
    

    When you bind to a document, you can freely create and destroy a.foo elements and they will all respond to your function.

    BIND TO ELEMENT:

    $("a.foo").on("click", function(event){
    //do stuff here
      });
    

    When you bind to an element, the function is bound to all previously existing elements ONLY. So make sure you do this at the end of document load or at the end of your function.

    I would recommend always binding to document!

    0 讨论(0)
  • 2021-01-13 08:17

    Try binding the function within the scope of the function where you dynamically create the element.

    $('a.foo').on('click',function(event){
     //your code goes here
    });
    
    0 讨论(0)
  • 2021-01-13 08:27

    Two things come to my mind:

    1. The link has no text so you are not clicking it.
    2. You aren't even appending it to the dom.

    Here there is a fiddle that works with code very similar to yours.

    var a = $('<a class="foo" href="#">ASD</a>');
    
    a.click(function() {
        alert('a');
    });
    
    a.appendTo($("body"));
    
    0 讨论(0)
提交回复
热议问题