2013-10-07 28 views
-1

是否有一種很好的方法可以做到這一點?你能發送原始值以及新的值到jquery/javascript函數嗎?保持一些全球變量的舊價值只是感覺有點混亂。檢測輸入類型「數量」是否從之前的值增加或減少

編輯:上下文代碼

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

... 

<script type=text/javascript> 
function foo(...){ 
    if(old > new){ 
     alert('decreased'); 
    }else{ 
     alert('increased'); 
    } 
} 
</text> 
+0

我們可以看到一些上下文代碼嗎? – Steve

+1

你將不得不保留舊的價值,並在範圍內。如果您在全球空間工作,那麼您必須將其存儲在全球範圍內。您可以考慮包裝代碼,以免污染全球空間。 。 。 – Julio

回答

3

所以不要把它放在一個全局變量:

<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(); 

JS Fiddle demo

你也可以,代替this.getAttribute('value') === this.value改用this.defaultValue === this.value(如本JS Fiddle demo),this.defaultValue正對DOM就緒元素的原始值。

參考文獻:

+0

不應該是'this.getAttribute('lastvalue')'? – Steve

+0

不,因爲** a)**不存在'lastvalue'屬性* *和** b)** if僅僅是爲了在第一次運行時建立數據對象的lastvalue屬性通過鏈中最後一行的'change()')。 (\ * data()'方法的某些屬性等同於'data- *'前綴屬性(如果它們存在的話),但不會更新這些屬性,並將它們保存在一個對象中供以後訪問。) –

+1

,我現在看到你在那裏做了什麼... :)但是,這不會從6到5(從之前的5到6增加之後)減少? – Steve