on()观察输入的变化(on() to watch changes in input)

编程入门 行业动态 更新时间:2024-10-27 20:27:31
on()观察输入的变化(on() to watch changes in input) $("#myTextBox").on("change paste keyup", function() { alert($(this).val()); });

如何比较用户插入的新值和输入中已存在的当前值?

$("#myTextBox").on("change paste keyup", function() { alert($(this).val()); });

How can I compare the new value inserted by the user and the current value that already existed in the input?

最满意答案

奇怪的是,输入的value属性在其值更改时实际上并未更新。 因此,您可以简单地将.val()与attr("value")并在进行更改后更新attr("value") :

例如:

$("#myTextBox").on("change paste keyup", function() {
   alert($(this).attr("value")+" vs "+$(this).val());
   $(this).attr("value",$(this).val());
}); 
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextBox" value="abc" /> 
  
 

Weirdly, the input's value attribute is not actually updated when its value is changed. Therefore you can simply compare the .val() to the attr("value") and update the attr("value") after a change is made:

E.G:

$("#myTextBox").on("change paste keyup", function() {
   alert($(this).attr("value")+" vs "+$(this).val());
   $(this).attr("value",$(this).val());
}); 
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextBox" value="abc" /> 
  
 

更多推荐

本文发布于:2023-08-07 05:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461173.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:watch   input

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!