1

我在 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));
});
4

5 回答 5

2

像这样:只是为了演示: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/

您可以指定任意数量的选择器组合成一个结果。这种多表达式组合器是选择不同元素的有效方法。返回的 jQuery 对象中的 DOM 元素的顺序可能不相同,因为它们将按文档顺序排列。此组合器的替代方法是 .add() 方法。

于 2013-10-05T06:07:06.123 回答
1

尝试这个

$('#phone,#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});
于 2013-10-05T06:08:35.850 回答
1

给两个元素相同的类并按它们的类选择它们,然后对两个元素做同样的事情。

于 2013-10-05T06:18:07.950 回答
0

jQuery 通常适用于集合。您可以传递多个以逗号分隔的选择器表达式。这将按您的要求工作。

$('#phone, #age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});
于 2013-10-05T06:13:48.800 回答
0

您可以,在选择器中使用多个选择

$('#phone,#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});
于 2013-10-05T06:16:44.743 回答