问:我将keydown分配给了只有2个键,但是,如果我按下任何键盘键,脚本就会被触发。有人可以通过查看脚本告诉我这是否是格式化问题?
这个keydown jQuery适合我,当按下右箭头时,模态移动到下一个,当按下左键时,它将触发前一个模态。
$("div[id^='myModal']").keydown(function(e){
var currentModal = $(this);
if (e.which == 39){
}else{
currentModal.modal('hide');
currentModal.closest("div[id^='myModal']").prevAll("div[id^='myModal']").first().modal('show');
}
var currentModal = $(this);
if (e.which == 37){
}else{
currentModal.modal('hide');
currentModal.closest("div[id^='myModal']").nextAll("div[id^='myModal']").first().modal('show');
}
});
使用if
语句会产生问题。看起来好像你应该改变你的代码:
$("div[id^='myModal']").keydown(function(e){
var currentModal = $(this);
if (e.which === 39) {
currentModal.modal('hide');
currentModal.closest("div[id^='myModal']").prevAll("div[id^='myModal']").first().modal('show');
} else if (e.which === 37) {
currentModal.modal('hide');
currentModal.closest("div[id^='myModal']").nextAll("div[id^='myModal']").first().modal('show');
}
});
基本上,你的代码所说的是“如果按下左箭头键什么也不做,否则用先前的模态执行某些操作”然后“如果按下右箭头键则不执行任何操作,否则使用下一个模式执行某些操作”。