首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将jquery代码块重构为一个块

如何将jquery代码块重构为一个块
EN

Stack Overflow用户
提问于 2022-07-13 04:45:55
回答 3查看 24关注 0票数 0

我有一些这样的jquery代码:

代码语言:javascript
复制
    $("#inputMobile").keypress(function(event){
        var ew = event.which;
        if(48 <= ew && ew <= 57)
            return true;
        if(65 <= ew && ew <= 90)
            return true;
        if(97 <= ew && ew <= 122)
            return true;
        alert("Change your keyboard language to English");
    });

    $("#inputEmail").keypress(function(event){
        var ew = event.which;
        if(48 <= ew && ew <= 57)
            return true;
        if(65 <= ew && ew <= 90)
            return true;
        if(97 <= ew && ew <= 122)
            return true;
        alert("Change your keyboard language to English");
    });

如您所见,主要函数是相同的,但是输入id是不同的,因为我想将它应用到两个输入字段中。

所以我的问题是,我如何将这段代码重构成一个函数块并删除额外的代码呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-07-13 04:47:10

回调函数是相同的,所以只需将选择器组合成一个。

代码语言:javascript
复制
$("#inputMobile, #inputEmail").keypress(function(event){
    var ew = event.which;
    if(48 <= ew && ew <= 57)
        return true;
    if(65 <= ew && ew <= 90)
        return true;
    if(97 <= ew && ew <= 122)
        return true;
    alert("Change your keyboard language to English");
});

注意,.which is deprecated。最好使用.key.code来检查按下了哪个键。您还可以将检查压缩为一个简洁的正则表达式。

代码语言:javascript
复制
$("#inputMobile, #inputEmail").keypress(function(event){
    if (/[\da-z]/i.test(event.key)) {
        return true;
    }
    alert("Change your keyboard language to English");
});

您还可以考虑使用proper modal instead of alert,即使在英文键盘上也可以按下非字母数字字符。更精确的信息应该是“只允许字母数字字符”之类的信息。

票数 2
EN

Stack Overflow用户

发布于 2022-07-13 04:48:48

代码语言:javascript
复制
const handler = function(event) {
  var ew = event.which;
  if (48 <= ew && ew <= 57)
    return true;
  if (65 <= ew && ew <= 90)
    return true;
  if (97 <= ew && ew <= 122)
    return true;

  alert("Change your keyboard language to English");
};
    
["#inputMobile", "#inputEmail"].forEach(selector -> $(selector).keypress(handler));
票数 0
EN

Stack Overflow用户

发布于 2022-07-13 04:49:32

代码语言:javascript
复制
function handleKeypress(id){
    $(`#${id}`).keypress(function(event){
        var ew = event.which;
        if(48 <= ew && ew <= 57)
            return true;
        if(65 <= ew && ew <= 90)
            return true;
        if(97 <= ew && ew <= 122)
            return true;
        alert("Change your keyboard language to English");
    });
}

现在,您可以使用handleKeypress("inputMobile")handleKeypress("inputEmail")调用它。

希望它能帮上忙

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72961058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档