如何使用委托事件? [英] How to use delegated events?

查看:137
本文介绍了如何使用委托事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个事件来替换某些图层中的src属性(< div class =total-titlesrc =anURL> ) :$ {


$ b $($。 #mp3-list ul li',this).each(function(index,element){
$('。total-title')。eq(index).attr('src',$(this)。 text());
});

它第一次工作,但不是在Ajax请求之后,当 $('。playOnAP')元素被替换时,我猜我应该使用委托事件,但不要自己清楚。



我尝试了下一个:

  $('。playOnAP')on('click','#mp3-list ($ click $,function(){
$('。playOnAP#mp3-list ul li')。on('click','#mp3-list ul li',function(){

但不起作用。

解决方案

尝试这样:

  $(document).on('click','.playOnAP',function(){
pre>

使用事件委托时,您必须将事件绑定到最初在DOM中的元素。如果某些东西已被动态替换,那么您无法绑定到。



作为Anup有见地提到,将点击事件绑定到文件 - 任何父元素都可以做,只要它最初在DOM中。



例如,如果 .playOnAP 是被替换的最顶层的容器元素:

 < div id = someDiv> 
< div class =playOnAP>
//某些东西在这里
< / div>
< / div>

您可以使用:

  $('#someDiv')。on('click','.playOnAP',function(){//做你的东西}); 

尽管如此,您几乎总是使用 $(document ).on()(即使只是快速检查,以确保一切正常,然后缩小到最合适的元素)。


I'm using an event to replace "src" attributes in some layers (<div class="total-title" src="anURL">):

$('.playOnAP').on('click',function() {
    $('#mp3-list ul li',this).each( function( index, element ) {
    $('.total-title').eq(index).attr('src', $(this).text() );
});     

and it works the first time, but not after an Ajax request, when the $('.playOnAP') elements are replaced. I'm guessing I should use Delegated Events, but don't make myself clear.

I've tried the next:

$('.playOnAP').on('click','#mp3-list ul li',function() {
$('.playOnAP #mp3-list ul li').on('click',function() {
$('.playOnAP #mp3-list ul li').on('click','#mp3-list ul li',function() {

but doesn't work.

解决方案

Try this:

$(document).on('click', '.playOnAP',function() {

When using event delegation, you must bind the event to an element that was originally in the DOM. If something has been dynamically replaced, you cannot bind to that.

As Anup insightfully mentioned, it is not strictly necessary to bind the click event to document -- any parent element will do, as long as it was originally in the DOM.

For example, if .playOnAP is the topmost container element that is being replaced:

<div id="someDiv">
    <div class="playOnAP">
        //some stuff here
    </div>
</div>

You could use:

$('#someDiv').on('click', '.playOnAP', function() { //do your stuff });

As a default, though, you can pretty much always use $(document).on() (even if just as a quick check to make sure everything works before narrowing down to the most appropriate element).

这篇关于如何使用委托事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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