我有两个按钮:
<button type="button" id="foo">off</button>
<button type="button" id="bar">on</button>
我有一个控制台,每1秒记录一次&#34; on&#34;:
function disable() {
console.log("on");
}
window.setInterval(function () {
disable();
}, 1000);
#foo
按钮会停止记录,如下所示:
$("#foo").click(function () {
window.disable = function () {
//aborted
};
});
并且#bar
按钮继续记录如下:
$("#bar").click(function () {
window.disable = function disable() {
console.log("on");
};
});
我希望能够通过使用切换来使两个按钮成为一个按钮
我试过这个。但它只是让按钮消失了?!!
$("#target").click(function () {
$(this).toggle(function () {
window.disable = function () {
//aborted
};
}, function () {
window.disable = function disable() {
console.log("on");
};
});
});
答案 0 :(得分:0)
toggle
。我认为正确且易于阅读的代码版本是将计时器设置为变量,并标记计时器是否正在运行。检查该标志,并清除或启用计时器:
function disable() {
console.log("on");
}
$(document).ready(function () {
var timer = false;
$("#foo").click(function () {
if (timer) {
clearTimeout(timer)
timer = false;
} else {
timer = setInterval(disable, 1000);
timer = true;
}
});
});
HTML:
<button type="button" id="foo">toggle</button>
答案 1 :(得分:0)
HTML
&lt; button type =“button”class =“foo”&gt; off&lt; / button&gt;
&lt; button type =“button2”class =“bar”&lt; on&gt; / button&gt;
&lt; button type =“button”id =“fop”&lt; toggle&gt; / button&gt;
function disable() {
console.log("on");
}
window.setInterval(function () {
disable();
}, 1000);
$(document).ready(function () {
var flag=true;
$("#fop").click(function () {
flag=flag?false:true;
if(flag){
$('.foo').attr('disabled','disabled');
$('.bar').removeAttr('disabled');
$(".foo").click();
}else{
$('.bar').attr('disabled','disabled');
$('.foo').removeAttr('disabled');
$(".bar").click();
};
});
$(".foo").on("click",function () {
window.disable = function () {
//aborted
};
});
$(".bar").on("click",function () {
window.disable = function disable() {
console.log("on");
};
});
});
查看此fiddle