尝试更好地理解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");
});
});
HTML
<div id="TurnOn">Turn Off</div>
<div id="TurnOff">Turn On</div>
答案 0 :(得分: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");
});
});
以下是使用.one()
:http://jsfiddle.net/9qxfT/1/
此外,您的代码恰到好处,但您在此处有一些拼写错误:
$(document).on("click.turnoff","#TurnOff",function() {
$(document).on('click.turnon');
alert("Turn Off is now turned back on");
});
$(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");
});
});
答案 1 :(得分:4)
你的逻辑是对的,但我可以建议更好的实施吗?
请同时阅读此页:http://api.jquery.com/off/
以下是我的建议:
// first put a .click event with a separate "ID" to enable another div "ID".
$('#ButtonForTurnOn').click(function () {
//while body is .on(), the ID, when clicked applies whatever effects
$("body").on("click", "#TurnOn", onlight).find("#TurnOn").addClass("clickable").text("ON switch on");
});
// enable OFF switch
$('#ButtonForTurnOff').click(function () {
$("body").on("click", "#TurnOff", offlight).find("#TurnOff").addClass("clickable").text("OFF switch on");
});
现在,为了让你有一个有效的.off
功能,你必须拥有
“选择器字符串匹配事件处理程序时传递给.on()的字符串 附上了。“
例如:
如果您的$("body").on()
是这个,
$("body").on("click", "#TurnOff", function({
// stuff here
});
您的$("body").off()
应为此,
$("body").off("click", "#TurnOff", function({
// stuff here
});
试试这个jsfiddle
希望这有助于解释事情! 只要将其视为禁用某些东西,直到它重新开启。