Sea*_*anW 75 html javascript forms jquery events
我今天早上一直在寻找,我找不到任何简单的解决方案...基本上,我想捕获输入元素的变化,但也知道以前的值.
这是一个更改事件和最简单形式的输入元素.显然,我可以使用$(elem).val()来获取新值,但是我是否因为获得之前的值而缺少一个偷偷摸摸的方法?我没有在jQuery API中看到任何东西来执行此操作,但也许有人已经完成了这个并且有一些提示?
<script>
$(document).ready(function(){
$('#myInputElement').bind('change', function(){
//var oldvalue = ???
var newvalue = $(this).val();
});
});
</script>
<input id="myInputElement" type="text">
Run Code Online (Sandbox Code Playgroud)
我不反对编写我自己的解决方案,我只是想确保我不在这里重新创建轮子.
red*_*are 104
更好的方法是使用.data存储旧值.这样可以避免创建一个全局变量,您应该远离该变量并将信息封装在元素中.一个真实的例子,为什么全局变量是不好的记录在这里
例如
<script>
//look no global needed:)
$(document).ready(function(){
// Get the initial value
var $el = $('#myInputElement');
$el.data('oldVal', $el.val() );
$el.change(function(){
//store new value
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
})
.focus(function(){
// Get the value when input gains focus
var oldValue = $(this).data('oldVal');
});
});
</script>
<input id="myInputElement" type="text">
Run Code Online (Sandbox Code Playgroud)
Sal*_*n A 16
这可能会成功:
$(document).ready(function() {
$("input[type=text]").change(function() {
$(this).data("old", $(this).data("new") || "");
$(this).data("new", $(this).val());
console.log($(this).data("old"));
console.log($(this).data("new"));
});
});
Run Code Online (Sandbox Code Playgroud)
$('#element').on('change', function() {
$(this).val($(this).prop("defaultValue"));
});
Run Code Online (Sandbox Code Playgroud)