简体   繁体   中英

Trying to do some jquery code after append

I have some links and I want something to happen when I click on the link. However, I'm creating these elements with.append This is my jQuery code:

$(".ClickTools").click(function(){alert(1);});

It doesn't work after the.append, but it does work when the element is there already (without using append). I need this code to work even when the element has been added to the page with append

This is html code:

<div id="appender"></div>

And this is my jQuery append code:

$("#appender).append('<a class=".ClickTools">click on me</a>');

When I click on the Click on me button, nothing happens. Can anyone explain why?

Do it this way:

$('<a>click on me</a>').appendTo('#appender').click(function(){alert(1);});

Using appendTo will allow your created object to be returned last, so you can directly add a click event to it.

as the dom-element is not existent on parsing, you have to bind event to an element that´s already there, eg document:

$(document).on('click', '.ClickTools',function(){ console.log(123) });

Also you dont need the dot (.) while appending and setting classname (fixed also the missing quote )

$("#appender").append('<a class="ClickTools">click on me</a>');

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