Getting access to a jquery element that was just appended to the DOM

后端 未结 7 829
耶瑟儿~
耶瑟儿~ 2020-12-08 18:34

I am simply appending an element that is on the DOM like:

$(\"#div_element\").append(\'test\');

Right after I

相关标签:
7条回答
  • 2020-12-08 18:54

    Just attach the click handler to the anchor BEFORE you append it.

    $("#div_element").append($('<a href="#">test</a>').click(function(){alert("test")}));
    
    0 讨论(0)
  • 2020-12-08 18:56

    You can attach event to element when you create it --

    var ele =$("<a href='#'>Link</a>");
    
    ele.on("click",function(){
        alert("clicked");
    });
    
    
    $("#div_element").append(ele);
    
    0 讨论(0)
  • 2020-12-08 19:00

    The last element would be the new element

    $('a:last','#div_element').on('click',function(){
        // do something
    });
    
    0 讨论(0)
  • 2020-12-08 19:01
    var $a = $('<a />', {href:"#"})
      .text("test")
      .on('click', function(e) { 
         alert('Hello') 
      })
      .appendTo('#div_element');
    

    http://jsfiddle.net/33jX4/

    0 讨论(0)
  • 2020-12-08 19:05

    Why not save a reference to the new element before you append it:

    var newElement = $('<a href="#">test</a>');
    $("#div_element").append(newElement);
    newElement.click(function(){alert("test")});  
    
    0 讨论(0)
  • 2020-12-08 19:06

    Add identity to that element then use it as follows

    $("#div_element").append('<a id="tester" href="#">test</a>');
    
    
    $('#tester').on('click', function(event) {
    console.log('tester clicked');
    });
    
    0 讨论(0)
提交回复
热议问题