开发者

Turn function on and off

I have a jQuery tip function. I would like to create a button to turn on and turn off the function. I want it to be on by def开发者_如何学Goault.

Is it possible to create a link to turn on and off a function?


You can dynamically add and subtract event handlers with the bind and unbind functions.

$("#id").click( function() {

    if ( HANDLER_IS_SET )
        $("#button").unbind( "click");    
    else       
        $("#button").bind( "click", myEventHandlerFunction );             
}


You can set a boolean to check if it's on or off, or bind and unbind a function.

var isOn = false;

$("#button").click(function(){ isOn = !isOn; });

$("#executebutton").click(MyFunction);

function MyFunction()
{
    if (!isOn) return;
    // do stuff
}

or

$("#button").click
(
    function()
    {
        if ($("#executebutton").data("events").click != undefined)
            $("#executebutton").unbind("click");
        else
            $("#executebutton").bind("click", MyFunction);
    }
);


A little more info is needed, but you could use a global variable to toggle an if statement within the function so it doesn't execute anything, but the function will still be called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜