首先从插件中取消绑定旧的点击功能,然后绑定新的

First unbind old click function from plugin and then bind new one

本文关键字:绑定 然后 功能 插件 取消      更新时间:2023-09-26

我有一个网站滑块功能,那里有一个下一个按钮。当没有其他幻灯片时,我想解除前一个点击功能的绑定并对点击按钮做一些其他的事情。

这是js

jQuery(document).bind('DOMSubtreeModified', function() {
  var button = jQuery("._disabled").length;
  if (button) {
    jQuery( "._next" ).off("click");
    jQuery( "._disabled" ).on("click", handler);
  }
  var handler = function (e) {
    e.preventDefault();
    jQuery('.suggested').show();
    jQuery('.theiaPostSlider_slides').html('');
    jQuery('.theiaPostSlider_slides').append(jQuery('.suggested'));
    jQuery('._buttons').hide();    
  }
});

按钮的HTML在这里:

<a rel="next" href="#" class="_button _next _disabled">
  <span class="_1">Next</span>
  <span class="_2"><span aria-hidden="true" class="tps-icon-chevron-circle-right"></span></span>
  <span class="_3"></span>
</a>

这是网站链接当你点击一次下一步按钮,它正常工作,然后当它在最后一张幻灯片上,它应该解除绑定,然后绑定新的功能,但它只是解除绑定。

我在这里做错了什么?

使用.on.off的方法就是使用.bind.unbind的方法

如果你的jQuery版本小于3,你可以这样修改:

    jQuery( "._next" ).unbind("click");
    jQuery( "._disabled" ).bind("click", handler);

否则,可以使用正确的格式保留.on.off。像这样:

    jQuery( 'body' ).off("click", "._next");
    jQuery( 'body' ).on("click", "._disabled", handler);

更多信息:http://api.jquery.com/unbind/

http://api.jquery.com/off/