不能多次执行一个jQuery函数

Can't execute a jQuery function more than once

本文关键字:一个 jQuery 函数 执行 不能      更新时间:2023-09-26

我有以下功能:

$('#edit').on("click", function () {
    $('#edit').text('click1');
    $('table a').click(function (e) {
        e.preventDefault();
    });
    $('table a').css("cursor", "default");
        }
    });
    $('#edit').click(function () {
        $('#edit').unbind();
        $('#edit-message-placeholder').empty();
        $('#edit').text('click2');
        $("table tbody").sortable("disable");
        $('table a').unbind()
        $('table a').css("cursor", "auto");
    });
});

在第一次单击时,我希望它改变div#edit的文本。在第二次点击时,它会将文本更改为其他内容。在第三次单击时,该函数的行为将像第一次单击一样。

我试着在网上寻找解决办法,但没有找到有用的。

问题是您处理这个问题的方法不正确。您不需要绑定/取消绑定事件处理程序。您只需要一个在功能上交替的事件处理程序:

JavaScript

var isOkay = true;
$("p").click(function () {
    if (isOkay) {
        $(this).text("1st click");
    } else {
        $(this).text("2nd click");
    }
    isOkay = !isOkay;
})

<p>Click me!</p>

每次单击<p>时,它执行一个动作,然后切换布尔变量isOkay的值。这意味着它将在ifelse块之间交替。注意,isOkay变量保存在$("p").click(...)事件处理程序的范围之外。

<标题>小提琴

试试这个-

使用data属性临时保存计数器数据

<button id="edit" data-count="1">1</button>

function doWork(val){
    alert(val);
};
$('#edit').on("click", function () {
    if($(this).data('count') == ""){
        $(this).data('count') = 1;
    }
    var count = parseInt($(this).data('count'));
    if (count == 1){
        doWork(count);
    }else if (count == 2){
        doWork(count);
    }else if (count == 3){
        doWork(count);
    }
    count += 1
    count = count >= 4 ? 1: count;
    $(this).data('count', count);
    $(this).html($(this).data('count'));
});

这里是jsfiddle - http://jsfiddle.net/pt3zE/1/