Change the button's function with jQuery?

我只是一个虾纸丫 提交于 2019-12-04 11:14:24

Something like the below code would work.

$("#click-button").on('click', firstClick)

function firstClick() {
    alert("First Clicked");
    $("#click-button").off('click').on('click', secondClick)
}

function secondClick() {
    alert("Second Clicked");
    $("#click-button").off('click').on('click', firstClick)
}

Working example here: http://jsfiddle.net/K3Xk4/

You don't need to change the handler every time. You can use a function and a variable to check if you already clicked the button (or not).

var even = false;

$('#click-button').click(function() {
    if(even) {
        doEven();
    } else {
        doOdd();
    }

    even = !even;
});

function doOdd() {
    // first click, third click, fifth click, etc
}

function doEven() {
    // second click, fourth click, sixth click, etc
}
Subodh Ghulaxe

You can simply do like this

<button id="click-button">test</button>

    var flag = 1;
    $("#click-button").click(function(){
        if(flag == 2){
            secondClick(); flag = 1;
        }else{
            firstClick(); flag = 2;
        }
    });

    function firstClick(){
        alert("First Click.");
    }

    function secondClick(){
        alert("Second Click.")
    }

check here http://jsfiddle.net/K3Xk4/5/

I'd go with custom events and data handling:

$('#click-button').on({
    firstClick : function()
    {
        // do something
        alert(111);

        // switch back
        $(this).data('nextClick', 'secondClick');
    },

    secondClick : function()
    {
        // do something
        alert(222);

        // switch back
        $(this).data('nextClick', 'firstClick');
    },

    click : function()
    {
        var nextClick = $(this).data('nextClick') || 'firstClick';
        $(this).trigger( nextClick );
    }
});

Example here: http://jsfiddle.net/psycketom/nbSMg/

You keep all the time with the same elements scope, no need to define variables outside the functions.

Might be a little overkill, but is the easiest to maintain.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!