首页 > 解决方案 > 当javascript更改输入值时触发更改或输入

问题描述

我正在用JQuery做一个小项目进行一个小项目,并且在从 html 元素中删除错误类时遇到问题。

$('selector').on('input')用来获取事件并删除input类,我的问题是使用 JavaScript 生成字段时;

例子

  $('#one').on('input',function(){
        $('#two').val(  $('#one').val()  );
    });


    $(':input').on('input', function ()
    {
        if ($(this).hasClass('example'))
        {
            $(this).removeClass('example');
        }
    });
 .example
    {
        color: orange;
        background-color: black;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Normal Case</h2>
        <input type="text" class="example">

        <h2>Problem</h2>
        <label for="one">#ONE</label>
        <input type="text" class="example" id="one">
        <br/>
        <label for="two">#TWO</label>
        <input type="text" class="example" readonly="readonly" id="two">

在这种情况下,我在更改#two时更改值#one#one删除.example#two

我需要从中删除.example课程#two input

编辑:我想以一种通用的方式来做,因为我的项目中有很多这样的案例

有什么方法可以触发这种变化吗?

非常感谢!

标签: javascriptjqueryhtmlevent-handling

解决方案


在语句的true分支中,使用该方法以及一个选择器来查找下一个以下. 这样,当第一个输入删除了类时,其后的下一个输入也将删除其类。if.nextAll()inputthis

此外,更改您的input事件设置,使其首先设置为对input某个类的元素起作用,并为每组inputs 中的第一个提供该类。

$('#one').on('input',function(){
  $('#two').val(  $('#one').val()  );
});

// Only when an input with the "input" class gets input
$('input.input').on('input', function () {
  if ($(this).hasClass('input')) {
     $(this).removeClass('input');
     
     // Find the next input sibling that follows "this"
     $(this).nextAll("input").removeClass("input");
  }
});
.input {
  color: orange;
  background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Normal Case</h2>
<input type="text" class="input">

<h2>Problem</h2>
<label for="one">#ONE</label>
<input type="text" class="input" id="one">
<br>
<label for="two">#TWO</label>
<input type="text" class="input" readonly="readonly" id="two">


推荐阅读