后来插入的标签没有被JQuery看到 [英] Later-inserted tags not seen by JQuery

查看:47
本文介绍了后来插入的标签没有被JQuery看到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < script language =javascript> 
$(document).ready(function(){
$(。test)。click(function(){
alert('Hello');
}) ;
});
< / script>

为什么前面的代码不适用于后面添加的类test的元素例如:

  $('body')。append('< p class =test> ;试验< / p为H.'); 

因为发生的是当我点击前面的< p> 标记没有任何反应。



另外,如果我有这样的话:

 < div id =first> Edit me。< div id =second> Save me。< / div>< / div> 

我可以做文字描述吗?即控制 #first div的内容而不影响 #second div的内容?



谢谢。

解决方案

问题在于 .click()只会在方法执行时为DOM中可用的元素应用侦听器。您应该查看 .on()



使用 .on()您可以委托事件,例如:


$(b)$($)$ $ $ $ $ $ $ $ $ $
});

现在任何元素(当前和未来)与类 test 可用于您的身体将有一个点击事件监听器。


Say I have this code in my page:

<script language="javascript">
 $(document).ready(function() {
  $(".test").click(function() {
   alert('Hello');
  });
 });
</script>

Why doesn't the previous code apply to elements with the class "test" which I add later to the document like this for example:

$('body').append('<p class="test">Test</p>');

Because what happens is that when I click the previous <p> tag nothing happens.

Also, if I have this:

<div id="first">Edit me.<div id="second">Save me.</div></div>

Can I do what the text describes? that is, controlling the content of the #first div without affecting the content of the #second div?

Thank you.

解决方案

The problem is that .click() does only apply a listener for elements that are available in the DOM when the method is executed. You should take a look at .on() instead.

With .on() you can delegate the event, like this for instance:

$("body").on("click", ".test", function() {
   alert('Hello');
});

Now any element (current and future) with the class test available within your body will have a click-event listener.

这篇关于后来插入的标签没有被JQuery看到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆