当按下重置按钮时,我试图绑定开始按钮。当按下“开始”按钮时,它会解除绑定,这是“单击”事件。但是我想要它,所以当点击重置按钮时,它会绑定开始按钮的单击事件,这样就可以再次按下它。下面这些都不起作用。有什么想法吗?
//Start
$("#start").bind("click", function(){
$("#start").unbind('click')
addCompMove();
playerMove();
});
$("#reset").bind("click", function(){
$("#start").bind('click');
comp.length = 0;
player.length = 0;
hoverCount = 0;
score = 0;
console.log(comp)
}); 发布于 2015-12-10 23:52:34
自版本1.7以来,on()和off()是jQuery中绑定和取消绑定事件侦听器的首选方法。
与其使用匿名函数,不如声明它们。它更模块化,更容易理解,并且让你做你想做的事情。
$("#start").on("click", startClicked);
function startClicked(e){
$(this).off("click");
$("#reset").on("click", resetClicked);
// other start stuff
}
function resetClicked(e){
$(this).off("click");
$("#start").on("click", startClicked);
// other reset stuff
}其他一些答案的问题在于,您将很容易地得到一个事件侦听器的多个实例,这些实例堆叠在一起,所有这些都是由一次单击触发的。如果多次单击"reset“,您将得到"start”事件侦听器的许多绑定,而这些绑定是您不想要的。根据您想要的功能,确保一次只允许一个按钮附加一个侦听器,或者解除所有以前的侦听器的绑定,并且只重新绑定您想要的侦听器。
发布于 2015-12-10 23:46:12
我建议创建一个函数来执行您的开始操作。
这样就可以更容易地将操作重新绑定到click事件,而不必每次都重新声明它们。
function startActions() {
$(this).unbind('click');
addCompMove();
playerMove();
}
$("#start").bind("click", startActions);
$("#reset").bind("click", function() {
$("#start").bind("click", startActions);
comp.length = 0;
player.length = 0;
hoverCount = 0;
score = 0;
console.log(comp);
});编辑
另外,在您的“重置”处理程序中,我建议在重新绑定单击事件之前先解除它的绑定。如果连续多次单击“重置”按钮,这将防止多个单击事件被绑定。
$("#start").unbind('click').bind("click", startActions);示范如下:
var $output=jQuery('div#output');
function startActions() {
$(this).unbind('click');
$output.html($output.html()+"<br />"+"Started");
}
$("#start").bind("click", startActions);
$("#reset").bind("click", function() {
$("#start").unbind('click').bind("click", startActions);
$output.empty();
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="start">START</button>
<button type="button" id="reset">RESET</button>
<div id="output"></div>
编辑
另一个想法是禁用按钮,而不是取消绑定事件:
var $output = jQuery('div#output'),
$start = jQuery('#start'),
$reset = jQuery('#reset');
$start.on("click", function() {
$output.html($output.html() + "<br />" + "Started");
$(this).prop('disabled', true);
$reset.prop('disabled', false);
});
$reset.on("click", function() {
$output.empty();
$(this).prop('disabled', true);
$start.prop('disabled', false);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="start">START</button>
<button type="button" id="reset" disabled>RESET</button>
<div id="output"></div>
发布于 2015-12-10 23:46:52
您想要取出要将单击绑定到的函数,以便可以根据需要添加和删除它。
var doMove = function(){
$("#start").unbind('click');
addCompMove();
playerMove();
}
$("#start").bind("click", doMove); // bind at start
$("#reset").bind("click", function(){
$("#start").bind('click', doMove); // bind again
comp.length = 0;
player.length = 0;
hoverCount = 0;
score = 0;
console.log(comp);
}); https://stackoverflow.com/questions/34213812
复制相似问题