javascript - 如何在一个函数中设置多个 id

标签 javascript jquery

我在 jquery 中有 2 个这样的函数:-

$('#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

$('#phone').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

这个拖车功能是一样的。

所以我需要像这样合并这个牵引功能:-

$('#phone') + $('#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

最佳答案

像这样:只是为了演示:http://jsfiddle.net/2ASnz/

您可以使用逗号组合多个选择器。

此链接将为您提供更多见解:http://api.jquery.com/multiple-selector/

希望这有助于:)

代码

$('#phone,#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

http://api.jquery.com/multiple-selector/

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the .add() method.

关于javascript - 如何在一个函数中设置多个 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19194595/

相关文章:

javascript - 逗号分隔字符串的总和

javascript - 如何知道 Rails 3 上 html 字段的 id?

javascript - 阻止加载混合事件内容 Mozilla 浏览器

jquery - 在禁用的文本区域上添加点击事件(jquery + ui)

c# - 带有回车键的文本框行号

javascript - 如何在给定新的 Firebase 响应的情况下更新 HTML 中的类?

javascript - 禁用的文本框

javascript - 创建动态 Two.js 变量以涉及单个点击事件

javascript - 将索引数组与 "Associative Array"混合

javascript - Bootstrap日期选择器: Changing start date to tomorrow