委托事件即使不应该触发也会触发

时间:2015-05-05 13:05:05

标签: javascript jquery events

我有以下代码:

 // Define controls
$('.play-video').click(function(){
    // Get the video element
    var video = $(this).parent().parent().find('video');
    // Play the video
    $(video).get(0).play()

    // Remove the play class and add the pause class so the same button will pause the video
    $(this).removeClass('play-video');
    $(this).addClass('pause-video');

    // Set pause text
    $(this).text('Pause');
});



$(document).on('click','.pause-video',function(){
    console.log('pausing...');
    // Get the video element
    var video = $(this).parent().parent().find('video');
    // Play the video
    $(video).get(0).pause()

    // Remove the play class and add the pause class so the same button will pause the video
    $(this).removeClass('pause-video');
    $(this).addClass('play-video');

    // Set pause text
    $(this).text('Play');
});

问题是,第二次点击事件应仅在

.pause-video
上触发,但也会在
.play-video
上触发

问题是:我做错了什么?

提前致谢, G3

4 个答案:

答案 0 :(得分:2)

你已经附上了" play"事件处理程序直接到按钮而不是使用委托。即使你改变了类,该处理程序也将继续触发。

委托通过事件冒泡工作,并且传递给.on()调用的选择器将在每个事件中重新检查。直接连接的处理程序不是这种情况:一旦处于活动状态,它们就会一直处于活动状态,直到它们被删除或直到删除DOM元素本身为止。改变DOM元素的细节不会有所作为。

因此可以通过在两种情况下使用委托来解决您的问题。

答案 1 :(得分:2)

你的代码很接近。但是你的第一个事件处理程序也需要委派:

$(document).on('click', '.play-video', click(function(){

答案 2 :(得分:1)

尝试停止immediage传播$(' .play-video')。点击

答案 3 :(得分:-1)

问题是jQuery无法动态跟踪对象变化。只需使用一次点击事件,并确定在此内做什么:

$('.play-stop-video').click(function(){
    if($(this).hasClass('play')) {
        // Current play button code here....
    }
    if($(this).hasClass('stop')) {
        // Current stop button code here....
    }
    $(this).toggleClass('play').toggleClass('stop');
});

$(某事).click(...会在页面加载时运行,并将点击事件附加到播放和停止按钮。但是,此时你没有任何停止按钮,所以点击事件将被丢弃...