简体   繁体   English

jQuery滑块自动播放按钮不起作用

[英]jQuery slider auto-play button didn't work

$('#btn-autoPlay.playoff').on('click', playOn);
$('#btn-autoPlay.playon').on('click', playOff);
function playOn() {

    $('.playoff').text("Autoplay: ON");
    timeId = setInterval(function () {
        nextSlide();
    }, 3000);
    $('.playoff').addClass('playon').removeClass('playoff');

}

function playOff() {

    $('.playon').text("Autoplay: OFF");
    clearInterval(timeId);
    $('.playon').addClass('playoff').removeClass('playon');

}

Details: When I first click button(#btn-autoplay.playoff), the text changes to "Autoplay: ON", as well as the class(.playoff) changes to class(.playon). 详细信息:当我第一次单击按钮(#btn-autoplay.playoff)时,文本更改为“自动播放:开”,并且class(.playoff)更改为class(.playon)。 But when I click the button second time, the button text doesn't change and the class is still '.playon'. 但是,当我第二次单击按钮时,按钮文本不会更改,并且该类仍为'.playon'。 What's wrong with this code? 此代码有什么问题?

Please try: 请试试:

$(document).on('click', '#btn-autoPlay.playoff', playOn);
$(document).on('click', '#btn-autoPlay.playon', playOff);

You may need to delegate the events for dynamically generated items. 您可能需要将事件委派给动态生成的项目。

The body is a static parent here and the events are watched with the help of the static parent. body在这里是静态父对象,并且在静态父对象的帮助下监视事件。 If some HTML gets changed dynamically by JavaScript, the connected events tend to disappear, as they are not the same old DOM Elements. 如果某些HTML通过JavaScript动态更改,则所连接的事件往往会消失,因为它们不是相同的旧DOM元素。

$("body").on('click', '#btn-autoPlay.playoff', playOn);
$("body").on('click', '#btn-autoPlay.playon', playOff);

So, attaching the event to a near static parent, and delegating it to the right one, will work for you. 因此,将事件附加到近乎静态的父对象,然后将其委托给正确的父对象,将对您有用。

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

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