我正在使用 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">
在这种情况下,当#one
更改时,我更改#two
值,#one
删除.example
但#two
没有
我需要从 #two
input
中删除 .example
类
编辑:我想以通用的方式来做,因为我的项目中有很多这样的案例
有什么方法可以触发这种变化吗?
非常感谢!
最佳答案
也许我下面写的代码对您有帮助。它并不完美,但它是一个很好的起点。
我为同一“组”的输入添加了一个名为data-group
的自定义属性。
我还修改了输入
的监听器,从单个监听器函数中,您将监听所有输入。
检查这是否对您有帮助。
$('.example').on('input',function(){
var value = this.value;
var groupName = $(this).attr('data-group');
var groupElems = $("[data-group='"+groupName+"']");
groupElems.removeClass('example');
groupElems.val(value);
});
.example
{
color: orange;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Problem</h2>
<label for="one">#ONE</label>
<input type="text" class="example" data-group="group1" id="one">
<br/>
<label for="two">#TWO</label>
<input type="text" class="example" data-group="group1" readonly="readonly" id="two">
<h2>Problem</h2>
<label for="three">#THREE</label>
<input type="text" class="example" data-group="group2" id="three">
<br/>
<label for="four">#FOUR</label>
<input type="text" class="example" data-group="group2" readonly="readonly" id="four">
<h2>Problem</h2>
<label for="five">#FIVE</label>
<input type="text" class="example" data-group="group3" id="five">
<br/>
<label for="six">#SIX</label>
<input type="text" class="example" data-group="group3" readonly="readonly" id="six">
关于javascript - 当javascript更改输入值时触发更改或输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50175100/