Jquery输入ID数组检测到更改

时间:2015-07-19 07:47:35

标签: javascript jquery arrays input detect

如果输入ID数组中有输入,我有一个关于检测更改的问题。

例如,我有一组输入ID:var arrayOfInputs = ['#firstname', '#lastname', '#email', '#phone'];

我的问题是我想检测这些字段中的任何输入更改,但我不想分别为每个输入字段编写庞大的脚本代码。

所以问题是:有没有办法用jQuery检测一行或两行代码中所有这些输入的输入变化?

也许我应该使用除ID数组之外的东西?

2 个答案:

答案 0 :(得分:2)

  

所以问题是:有没有办法用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>

答案 1 :(得分:1)

您可以使用 each()在排序代码中执行此操作。

var arrayOfInputs = ['#firstname', '#lastname', '#email', '#phone'];
$.each(arrayOfInputs, function(index, data){
  $(data).on('change',function(){
     alert($(this).val());
  });
});
相关问题