倾听单个输入的变化

Listen for change on a single input

本文关键字:变化 输入 单个 倾听      更新时间:2023-09-26

我有一个包含两个字段的表单,它们的值是通过编程填充的。当我通过JS更改值时,我正在使用.trigger('change'),然后用侦听此更改

$('body').on('change', $(myInput1), function() {});

$('body').on('change', $(myInput2), function() {});

问题是,如果我更改myInput1,两个侦听器都是活动的(就像我更改了两个输入一样)。

这里有一个小演示来重现这个问题:

$(document).ready(function() {
  $('a').click(function() {
    var randomValue = Math.random(0, 1) * 100;
    var holder = $(this).closest('.holder');
    holder.find('input').attr('value', randomValue);
    holder.find('input').trigger('change');
  });
  $('body').on('change', $('input[name="field_one"]'), function() {
    alert('field one has changed');
  });
  $('body').on('change', $('input[name="field_two"]'), function() {
    alert('field two has changed');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <div class="holder">
    <a href="#" class="field1">Change me</a>
    <input type="hidden" name="field_one" />
  </div>
  <div class="holder">
    <a href="#">Change me</a>
    <input type="hidden" name="field_two" />
  </div>
</form>

和jsfiddle演示

使用事件委派时,on的第二个参数应该是作为选择器的字符串。在您的情况下,您将传递一个jQuery对象作为第二个参数,因此事件注册将其视为数据对象,处理程序将注册到body元素,jQuery对象将在处理程序中作为event.data传递

$(document).ready(function() {
  $('a').click(function() {
    var randomValue = Math.random(0, 1) * 100;
    var holder = $(this).closest('.holder');
    holder.find('input').val(randomValue).change();
    //holder.find('input').attr('value', randomValue);
    //holder.find('input').trigger('change');
  });
  $('body').on('change', 'input[name="field_one"]', function() {
    snippet.log('field one has changed');
  });
  $('body').on('change', 'input[name="field_two"]', function() {
    snippet.log('field two has changed');
  });
  $('body').on('change', $('input[name="field_one"]'), function(e) {
    snippet.log('handler 1:' + this.tagName + ':' + e.data.selector);
  });
  $('body').on('change', $('input[name="field_two"]'), function(e) {
    snippet.log('handler 2:' + this.tagName + ':' + e.data.selector);
  });
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <div class="holder">
    <a href="#" class="field1">Change me</a>
    <input type="hidden" name="field_one" />
  </div>
  <div class="holder">
    <a href="#">Change me</a>
    <input type="hidden" name="field_two" />
  </div>
</form>

尝试FIDDLE

不要将第二个参数作为Jquery对象传递

尝试从更改选择器

$('body').on('change', $('input[name="field_one"]'), function(e) {

$('body').on('change','input[name=field_one]', function(e) {

希望它对你有用。