On()和off() - Jquery

Joe*_*Joe 2 javascript jquery

试图更好地理解Jquery的On()和off().不明白为什么这不起作用.我想激活和停用id TurnON和TurnOff Js.

使用Javascript

$(document).ready(function(){

    $(document).on("click.turnon","#TurnOn",function() {
        $(document).off('click.turnon');    
        alert("Turn Off is now turned off");
    });

    $(document).on("click.turnoff","#TurnOff",function() {
        $(document).on('click.turnon');
        alert("Turn Off is now turned back on");
    });

});
Run Code Online (Sandbox Code Playgroud)

HTML

<div id="TurnOn">Turn Off</div>
<div id="TurnOff">Turn On</div>
Run Code Online (Sandbox Code Playgroud)

Jas*_*per 7

如果您希望事件处理程序只触发一次,请查看.one():http://api.jquery.com/one

从jQuery 1.7开始,它执行事件委托.

$(function(){

    $(document).one("click.turnon","#TurnOn",function() {  
        alert("Turn Off is now turned off");
    });

    $(document).one("click.turnoff","#TurnOff",function() {
        alert("Turn Off is now turned back on");
    });

});
Run Code Online (Sandbox Code Playgroud)

这是一个使用的演示.one():http://jsfiddle.net/9qxfT/1/

此外,你的代码是正确的,但你有一些拼写错误:

$(document).on("click.turnoff","#TurnOff",function() {
    $(document).on('click.turnon');
    alert("Turn Off is now turned back on");
});
Run Code Online (Sandbox Code Playgroud)

$(document).on('click.turnon'); 应该: $(document).off('click.turnoff');

以下是这些小变化的演示:http://jsfiddle.net/9qxfT/

更新

您可以使用变量保存状态:

$(function(){

    //declare a variable to save whether or not the `#TurnOn` element is 'on' (true) or 'off' (false)
    var isOn = true;

    $(document).on("click.turnon","#TurnOn",function() {

        //check to see if the flag is set to true, which means the `#TurnOn` element is 'on' already
        if (isOn) {
            alert("#TurnOn is already turned on");

        //otherwise set the `#TurnOn` element to 'on'
        } else {
            alert("#TurnOn is now turned back on");
            isOn = true;
        }
    });

    //set the `#TurnOn` element to `off` when the `#TurnOff` element is clicked
    $(document).on("click.turnoff","#TurnOff",function() {
        isOn = false;
        alert("#TurnOn is now turned off");
    });

});?
Run Code Online (Sandbox Code Playgroud)

这是一个演示:http://jsfiddle.net/9qxfT/4/