jQuery想要在按钮点击时覆盖功能

时间:2016-05-30 15:34:25

标签: javascript jquery

我已经有一个jQuery .on()函数,其中click按钮传递了click事件。

我想限制用户单击按钮超过1但我不想改变当前功能而是编写新功能



$('button').on('click', function() {
    alert('hi');
});

$('button').click(function(event) {
    var count = 0;
    count = count + 1;
    if (count > 1) {
        event.preventDefault();
        console.log('dont call alert');
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button>Click Me !</button>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

我认为您正在寻找类似的内容。

&#13;
&#13;
Option Strict On
&#13;
$('button').on('click', function () {
    alert('hi');
});


var isCliked = true;
$('button').click(function () {
    $('button').off('click');

    isCliked && $('button').click(function() {
        console.log('dont call alert');
        isCliked = false;
    });
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用jQuery .one()方法:

&#13;
&#13;
$('button').one('click', function() {
    alert('hi');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button>Click Me !</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

JQuery off()方法删除元素的事件处理程序。您可以在点击时移除click按钮事件。使用此工作,按钮单击事件仅触发一次。

$("button").click(function(event){
    alert();
    $(this).off("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button</button>