Javascript 检测输入类型是否为';编号';与以前的值相比增加或减少
有什么好办法吗?可以将原始值和新值发送到jquery/javascript函数吗?将旧值保存在某个全局变量中感觉有点混乱 编辑:上下文代码Javascript 检测输入类型是否为';编号';与以前的值相比增加或减少,javascript,jquery,html,Javascript,Jquery,Html,有什么好办法吗?可以将原始值和新值发送到jquery/javascript函数吗?将旧值保存在某个全局变量中感觉有点混乱 编辑:上下文代码 <input type='number' onchange='foo(...)'> ... <script type=text/javascript> function foo(...){ if(old > new){ alert('decreased'); }else{ al
<input type='number' onchange='foo(...)'>
...
<script type=text/javascript>
function foo(...){
if(old > new){
alert('decreased');
}else{
alert('increased');
}
}
</text>
...
函数foo(…){
如果(旧的>新的){
警惕(“减少”);
}否则{
警惕(“增加”);
}
}
所以不要将其保存在全局变量中:
<input type="number" value="5" />
$('input[type="number"]').change(function () {
if (this.getAttribute('value') === this.value) {
// setting the original 'lastvalue' data property
$(this).data('lastvalue', this.value);
} else {
// take whatever action you require here:
console.log(this.value < $(this).data('lastvalue') ? 'decrement' : 'increment');
// update the lastvalue data property here:
$(this).data('lastvalue', this.value);
}
}).change();
$('input[type=“number”]”)。更改(函数(){
if(this.getAttribute('value')==this.value){
//设置原始“lastvalue”数据属性
$(this.data('lastvalue',this.value));
}否则{
//在此处采取您需要的任何行动:
console.log(this.value<$(this.data('lastvalue')?'decrement':'increment');
//在此处更新lastvalue数据属性:
$(this.data('lastvalue',this.value));
}
}).change();
您还可以使用this.getAttribute('value')===this.value
代替this.defaultValue===this.value
(如本例所示),this.defaultValue
是DOM ready上元素的原始值
参考资料:
<input type="number" value="5" />
$('input[type="number"]').change(function () {
if (this.getAttribute('value') === this.value) {
// setting the original 'lastvalue' data property
$(this).data('lastvalue', this.value);
} else {
// take whatever action you require here:
console.log(this.value < $(this).data('lastvalue') ? 'decrement' : 'increment');
// update the lastvalue data property here:
$(this).data('lastvalue', this.value);
}
}).change();
$('input[type=“number”]”)。更改(函数(){
if(this.getAttribute('value')==this.value){
//设置原始“lastvalue”数据属性
$(this.data('lastvalue',this.value));
}否则{
//在此处采取您需要的任何行动:
console.log(this.value<$(this.data('lastvalue')?'decrement':'increment');
//在此处更新lastvalue数据属性:
$(this.data('lastvalue',this.value));
}
}).change();
您还可以使用this.getAttribute('value')===this.value
代替this.defaultValue===this.value
(如本例所示),this.defaultValue
是DOM ready上元素的原始值
参考资料:
this.getAttribute('lastvalue')
?否,因为a)没有“lastvalue”属性*,b)if的只是在第一次运行时建立数据对象的lastvalue
属性(由链的最后一行中的change()
触发)。(*如果存在data()
方法,则该方法将包含一些与data-*
前缀属性相等的属性,但不会更新这些属性,并将它们保留在对象中以供以后访问。)哦,我现在明白了您在那里做的事情了…:)但是,这不会捕捉到从6到5的递减(在之前从5到6的增量之后)?这不应该是this.getAttribute('lastvalue')
?否,因为a)没有“lastvalue”属性*,b)如果只是在第一次运行时建立数据对象的lastvalue
属性(由链的最后一行中的change()
触发)。(*该data()
方法将包含一些与data-*
前缀属性相等的属性,如果它们存在,但不会更新这些属性,并将它们保留在对象中以供以后访问。)哦,我现在知道你在那里做了什么…:)但是,这不会捕获从6到5的减量(在之前从5到6的增量之后)?