防止jQuery.fn.extend多次触发

Prevent jQuery.fn.extend from firing multiple times

本文关键字:extend jQuery fn 防止      更新时间:2023-09-26

我举了以下示例

<script>
    $( "#buttom1" ).click(function() {
    console.log('ok')
    $.fn.thefuncion();

    });

    $.fn.thefuncion=function(){
    jQuery('#buttom2').click(function(){
     alert('ready')
     });
    }
</script>
    <input type="submit" name="button" id="buttom1" value="buttom 1">
    <input type="submit" name="button" id="buttom2" value="buttom 2">

问题是警报出现的次数是按下1按钮的次数

无论按下1按钮的次数如何,我都需要在按下按钮2后仅显示警报。

试着用正确的方式来做。不要多次绑定事件。这是没有必要的。你可以通过活动授权的形式来实现你想要的。

$( "#buttom1" ).click(function() {
    jQuery('#buttom2').addClass("active");
});
jQuery(document).on('click','.active', function(){
    alert('ready')
});

其中document将是事件冒泡的终点,由此触发事件的罪犯将被抓住,其事件将被触发(如果有的话)。因此,不需要遍历到文档。代替document传递按钮buttom2 的任何静态最近父级

演示

您可以使用jQuery .one()函数:

$( "#buttom1" ).one('click', function() {
    console.log('ok')
    $.fn.thefuncion();
});

此事件将在第一次单击按钮1时触发,按钮2事件将只设置一次。