简体   繁体   中英

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

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

$("#div_element").append('<a href="#">test</a>');

Right after I append it I need access to the element I just made in order to bind an click function to it, I tried:

$("#div_element").append('<a href="#">test</a>').click(function(){alert("test")});

But the above didn't work. I could uniquely id the element but that seems like a bit to much work when perhaps there is a way I can get the element right after I append it.

You can do this:

var el = $('<a href="#">test</a>');

$("#div_element").append(el);

el.click(function(){alert("test")});

// or preferrably:
el.on('click', function(){alert("test")});

The append function accepts two types of arguments: a string or a jQuery element. In case a string is passed in, it will create a jQuery element internally and append it to the parent element.

In this case, you want access to the jQuery element yourself, so you can attach the event handler. So instead of passing in the string and let jQuery create an element, you have to create the element first and then pass it to the append-function.

After you've done that, you still have access to the jQuery element to be able to attach the handler.

var $a = $('<a />', {href:"#"})
  .text("test")
  .on('click', function(e) { 
     alert('Hello') 
  })
  .appendTo('#div_element');

http://jsfiddle.net/33jX4/

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")});  

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');
});

The last element would be the new element

$('a:last','#div_element').on('click',function(){
    // do something
});

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);

只需将点击处理程序附加到锚点,然后再附加它。

$("#div_element").append($('<a href="#">test</a>').click(function(){alert("test")}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM