当前位置: 代码迷 >> JavaScript >> jQuery输入ID数组检测更改
  详细解决方案

jQuery输入ID数组检测更改

热度:47   发布时间:2023-06-13 12:32:04.0

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

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

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

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

也许我应该使用ID数组以外的其他东西?

所以问题是:有没有一种方法可以用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> 

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

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