jQuery on()方法只能通过childSelector间接工作 [英] jQuery on() method only works indirectly via childSelector

查看:624
本文介绍了jQuery on()方法只能通过childSelector间接工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法可能是代码的原因

  $('body')。on('click' '.btn_add',function(e){alert(test);}); 

工作,但

 on('click',function(e){alert(test);});  $('。btn_add' 

不?



谢谢, / p>

解决方案

是事件委托:



语法是:

  $(staticparent).on(event,selector,fn); 

在这种语法选择器不是一部分的DOM,当您的页面加载此元素不在dom中时,但在某些js代码执行后,在DOM中添加的 .btn_add 元素意味着什么。所以在页面加载中绑定的任何事件都不会被注册到这个元素。



所以在你的情况下,如果 .btn_add 是动态创建的,那么你必须将事件委托给最接近的静态父,身体或文档本身。



以下是事件未绑定的测试用例动态内容



  $('button')。on('click',function appendTo('body'); alert(this.textContent);}) 

 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1。 1 / jquery.min.js>< /脚本><按钮>静态< /按钮>  



这是一个动态公司绑定的事件的测试案例ntent



  $('body')。on('click','button' (){$('< button />',{text:动态按钮})。appendTo('body'); alert(this.textContent);}) 

 < script SRC = https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js >< /脚本><按钮>静态< /按钮>  


Any ideas what could be the reason that the code

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

works, but

$('.btn_add').on('click', function(e) {alert("test");});

does not?

Thanks,

解决方案

It is event delegation:

Syntax is :

$(staticparent).on(event, selector, fn);

in this syntax selector is not a part of DOM, what it means when your page loaded this element was not there in the dom but after some js code execution this .btn_add element added in the DOM. so any event bound on page load won't be registered for this element.

so in your case if .btn_add is created dynamically then you have to delegate the event to the closest static parent, body or to document itself.

Here is a test case for event not bound on dynamic content.

$('button').on('click', function() {
  $('<button/>', {
    text: "Dynamic button"
  }).appendTo('body');
  alert(this.textContent);

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Static</button>

Here is a test case for event bound on dynamic content.

$('body').on('click', 'button', function() {
  $('<button/>', {
    text: "Dynamic button"
  }).appendTo('body');
  alert(this.textContent);

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Static</button>

这篇关于jQuery on()方法只能通过childSelector间接工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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