检测输入类型“数字”是否比之前的值增加或减少

Hos*_*ser 2 html javascript jquery

有没有好的方法可以做到这一点?您可以将原始值和新值发送到 jquery/javascript 函数吗?将旧值保留在某个全局变量中感觉有点混乱。

编辑:上下文代码

<input type='number' onchange='foo(...)'>

...

<script type=text/javascript>
function foo(...){
    if(old > new){
        alert('decreased');
    }else{
        alert('increased');
    }
}
</text>
Run Code Online (Sandbox Code Playgroud)

Dav*_*mas 5

所以不要将其保存在全局变量中:

<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();
Run Code Online (Sandbox Code Playgroud)

JS 小提琴演示

您也可以代替this.getAttribute('value') === this.value使用this.defaultValue === this.value(如在这个JS Fiddle 演示中),this.defaultValue作为 DOM-ready 上元素的原始值。

参考:

  • 哦,我现在明白你在那里做了什么...:)但是,这不会捕获从 6 到 5 的减量(在之前从 5 到 6 的增量之后)? (2认同)