if-else语句太多了。他们可以成为全球性的吗?
I'm trying to streamline this script. I have 50 of these if e.keyCode
statements, so double nesting if/else statements seems ridiculous, but all other attempts I've made haven't worked.
我正在尝试简化这个脚本。我有50个这样的e.keyCode语句,所以双嵌套如果/ else语句看起来很荒谬,但我所做的所有其他尝试都没有用。
The first if/else statement if(e.keyCode == 66 && e.shiftKey)
is necessary, but I'm not sure about the second if (typedAdjusted >= paperWidth % charWidth)
which is throwing a warning if too many characters are typed on a line relative to a fixed width.
第一个if / else语句if(e.keyCode == 66 && e.shiftKey)是必要的,但是我不确定第二个if(typedAdjusted> = paperWidth%charWidth)如果字符太多则抛出警告在相对于固定宽度的线上键入。
Can the functionality if (typedAdjusted >= paperWidth % charWidth)
gives me be global? It will need to be checked against specific keyCodes. For instance, the letter "B" should be figured into typedAdjusted while BACKSPACE and TAB and COMMAND should not.
功能if(typedAdjusted> = paperWidth%charWidth)能否让我全球化?需要根据特定的keyCodes进行检查。例如,字母“B”应该计入typedAdjusted,而BACKSPACE和TAB和COMMAND不应该。
var typed = $("span.char").length;
var typedAdjusted = typed+1;
var paperWidth = 900;
var charWidth = 44;
if (e.keyCode == 66) {
if (e.keyCode == 66 && e.shiftKey) {
$('#charLine-1').append('<span class="char">B</span>');
if (typedAdjusted >= paperWidth % charWidth) {
$('body').append('<span id="warning">WARNING!</span>');
}
else {
return false;
}
}
else {
$('#charLine-1').append('<span class="char">b</span>');
if (typedAdjusted >= paperWidth % charWidth) {
$('body').append('<span id="warning">WARNING!</span>');
}
else {
return false;
}
}
}
3 个解决方案
#1
2
IF you like checking each one use a switch: call the checkKey function as needed passing the event.
如果你喜欢检查每一个,请使用一个开关:根据需要调用checkKey函数传递事件。
function checklen() {
var typed = $("span.char").length;
var typedAdjusted = typed + 1;
var paperWidth = 900;
var charWidth = 44;
return (typedAdjusted >= paperWidth % charWidth);
}
function checkKey(e) {
var mychar = '';
var checkit = false;
switch (e.keyCode) {
case 66:
mychar = e.shiftKey ? 'B' : 'b';
checkit = checklen();
break;
case 67:
mychar = e.shiftKey ? 'C' : 'c';
checkit = checklen();
break;
case 68:
mychar = e.shiftKey ? 'D' : 'd';
checkit = checklen();
break;
default:
checkit = false;
break;
}
if (!checkit) {
$('#charLine-1').append('<span class="char">' + mychar + '</span>');
}
else {
$('body').append('<span id="warning">WARNING!</span>');
}
}
to get it to work on the entire document:
让它在整个文档上工作:
$(document).ready(function(){
$(document).keydown(function(e) {
checkKey(e);
});
});
then just click on the page and type characters - note only 'b','c','d' on the code above.
然后只需点击页面并输入字符 - 请注意上面代码中的'b','c','d'。
更多相关文章
- NodeJS - 解析JSON(只有字符串或数字)
- 如何在JavaScript中对字符串排序
- 将特殊字符转换为HTML实体,Laravel
- JSON.parse(xhr.responseText)意外的字符串错误
- 奇怪的字符显示在XML> ASP.NET> Javascript> HTML中
- 如何在url中将特殊字符作为查询字符串传递
- JS计算任意字符串宽度
- 如何在JavaScript中按大写和小写分割字符串?
- 使用jackson json将属性添加到json字符串