【发布时间】:2021-07-11 07:22:28
【问题描述】:
这段代码有什么问题?它应该捕获 #ts_container div 中的所有点击,这些点击要么是按钮,要么是锚点。它还应该捕获按键事件。
我正在尝试在每个案例中应用一个 If 语句来确定是否按键和/或单击,如果是,它将新的 div 名称重写为开关案例底部的表达式,然后当前文本将淡出和新的文本淡入。W/o Keypress 它工作正常。正如现在所写的那样,当您单击时它仍然可以正常工作,但我无法让它触发按键事件,而且我不确定我做错了什么。
jQuery(document).ready(function($) {
$('#ts_container').on('click keypress', 'button, a', function(e) {
var id = $(this).attr("id");
var fade_out;
var fade_in;
switch (id) {
case 'start':
if ((e.type === 'keypress' && e.which === 13) || (e.type == 'click')) {
fade_out = '#start_1';
fade_in = '#step_0';
}
break;
case 'AC':
if ((e.type === 'keypress' && e.which === 49 || e.which === 97) || (e.type == 'click')) {
fade_out = '#step_0';
fade_in = '#step_AC_1';
}
break;
case 'step_AC_Continue_1':
if ((e.type === 'keypress' && e.which === 13) ||
(e.type == 'click')) {
fade_out = '#step_AC_1';
fade_in = '#step_AC_2';
}
break;
case 'Step_0_Option_1':
if ((e.type === 'keypress' && e.which === 50 || e.which === 98) || (e.type == 'click')) {
fade_out = '#step_0';
fade_in = '#step_Heat_1';
}
break;
case 'step_AC_Option_1':
if ((e.type === 'keypress' && e.which === 49 || e.which === 97) || (e.type == 'click')) {
fade_out = '#step_AC_2';
fade_in = '#step_AC_3';
}
break;
case 'step_AC_Option_2':
if ((e.type === 'keypress' && e.which === 50 || e.which === 98) || (e.type == 'click')) {
fade_out = '#step_AC_2';
fade_in = '#step_AC_solution_electrical';
}
break;
case 'step_AC_Option_3':
if ((e.type === 'keypress' && e.which === 51 || e.which === 99) || (e.type == 'click')) {
fade_out = '#step_AC_2';
fade_in = '#step_AC_circuit_breaker';
}
default:
fade_out = '#start_1';
fade_in = '#step_0';
}
$(fade_out).fadeTo('fast', 0).css('visibility', 'hidden')
.css('display', 'none');
$(fade_in).delay(800).css('visibility', 'visible')
.css('display', 'block').fadeTo('slow', 1);
});
});
【问题讨论】:
-
请添加正确缩进的代码,这样的代码很难调试。尝试添加调试器。
标签: javascript jquery onclick switch-statement keypress