javascript - 当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
编辑:我想以一种通用的方式来做,因为我的项目中有很多这样的案例
有什么方法可以触发这种变化吗?
非常感谢!
解决方案
在语句的true
分支中,使用该方法以及一个选择器来查找下一个以下. 这样,当第一个输入删除了类时,其后的下一个输入也将删除其类。if
.nextAll()
input
this
此外,更改您的input
事件设置,使其首先设置为对input
某个类的元素起作用,并为每组input
s 中的第一个提供该类。
$('#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">
推荐阅读
- python - 递归函数不返回python中的最新值
- rust - 在地图中存储异步回调
- cakephp - cakephp4 路由到未知路径
- interbase - 在 InterBase 中更改 SYSDBA 用户密码
- meteor - Meteor and Passenger 在流星构建中没有公用文件夹 --server-only
- botframework - 如何将消息活动从 Web Chat Bot 发送到 Microsoft Teams 频道
- python - 在 SQL Server 2014 中的 UPDATE 触发器后运行 Python 应用程序
- r - Geom_smooth 线未显示或未出现在 r 中的图形上
- internationalization - Hugo - 如何制作其他语言的页面
- python - 打印特定的请求头python