问题描述
我有一个关于检测输入ID数组中的输入是否更改的问题。
例如,我有一个输入ID数组: var arrayOfInputs = ['#firstname', '#lastname', '#email', '#phone'];
我的问题是我想检测这些字段中的任何输入更改,但是我不想为每个输入字段分别编写庞大的脚本代码。
所以问题是:有没有一种方法可以用jQuery的一行或两行代码来检测数组中所有这些输入的输入变化?
也许我应该使用ID数组以外的其他东西?
1楼
所以问题是:有没有一种方法可以用jQuery的一行或两行代码来检测数组中所有这些输入的输入变化?
是:
$(arrayOfInputs.join(",")).on("change", function() {
// Here, `this` will refer to the input that changed
});
现场演示 :
var arrayOfInputs = ['#firstname', '#lastname', '#email', '#phone']; $(arrayOfInputs.join(",")).on("change", function() { snippet.log(this.id + " changed"); });
<div><input type="text" id="firstname"></div> <div><input type="text" id="lastname"></div> <div><input type="text" id="email"></div> <div><input type="text" id="phone"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
也许我应该使用ID数组以外的其他东西?
是的,给它们一个通用的类或data-*
属性或其他东西,而不要列出ID。
现场演示 :
$(".watch-me").on("change", function() { snippet.log(this.id + " changed"); });
<div><input type="text" class="watch-me" id="firstname"></div> <div><input type="text" class="watch-me" id="lastname"></div> <div><input type="text" class="watch-me" id="email"></div> <div><input type="text" class="watch-me" id="phone"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
2楼
您可以使用each()在排序代码中执行该操作。
var arrayOfInputs = ['#firstname', '#lastname', '#email', '#phone'];
$.each(arrayOfInputs, function(index, data){
$(data).on('change',function(){
alert($(this).val());
});
});