简体   繁体   English

在 append 之后尝试做一些 jquery 代码

[英]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:但是,我正在使用.append 创建这些元素 这是我的 jQuery 代码:

$(".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).在.append 之后它不起作用,但是当元素已经存在时它确实起作用(不使用附加)。 I need this code to work even when the element has been added to the page with append即使已使用 append 将元素添加到页面,我也需要此代码才能工作

This is html code:这是 html 代码:

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

And this is my jQuery append code:这是我的 jQuery append 代码:

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

When I click on the Click on me button, nothing happens.当我单击“ Click on me ”按钮时,没有任何反应。 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.使用 appendTo 将允许您创建的 object 最后返回,因此您可以直接向其添加点击事件。

as the dom-element is not existent on parsing, you have to bind event to an element that´s already there, eg document:由于解析时不存在 dom 元素,因此您必须将事件绑定到已经存在的元素,例如文档:

$(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>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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