2016-08-16 92 views
1

我有一個輸入:jquery的,屬性選擇器,獲得當前屬性值

<input type="text" size="5" maxlength="5" decimals="2"> 

其中「小數」可以是從0到4

的值。在onblur事件,任何數字用戶類型將改爲符合,因此:

decimals="2" 
User enters: 123.456 
Input is changed to: 123.46 

這很平凡,沒問題。我的問題是關於獲得「小數」值的最有效方法。既然我們已經選擇了基於輸入

$('[decimals]').blur(function(){ 
    val = $(this).attr('decimals'); 
    // *** do stuff with val *** 
}); 

...但在我看來,就必須有一種更有效的方式來獲得「小數」的價值:通常情況下,我會寫(jQuery的)在那個屬性上。有沒有,或者我的代碼是唯一的寫法?

+0

的SERMs沒什麼問題 – Noppey

+2

如果您使用自定義屬性至少使用*有效*自定義屬性,使用'data-*'前綴,比如'data-decimals',可以用'elementReference.dataset.decimals'在普通的JavaScript中檢索,或者在jQuery中用'$(ele ('decimals');' –

+0

你在說'$(this)'嗎?如果你想調用'$ .attr',你不能避免它,但這幾乎是免費的(jQuery緩存),但你可以用'this.getAttribute('decimals')'讀取值也 – cske

回答

0

您可以看看attributes。這是一個NamedNodeMap有一些功能。

如果你指的是屬性而不是custom data attributes你可以這樣做:

$(function() { 
 
    $('[decimals]').blur(function(){ 
 
    var val = this.attributes.decimals.value; 
 
    var val1 = this.attributes.getNamedItem('decimals').value; 
 
    var val2 = this.getAttribute('decimals'); 
 
    
 
    console.log('this.attributes.decimals.value = ' + val); 
 
    console.log('this.attributes.getNamedItem("decimals").value = ' + val1); 
 
    console.log('this.getAttribute("decimals") = ' + val); 
 
    // *** do stuff with val *** 
 
    }).trigger('blur'); 
 
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
 

 
<form> 
 
    <input type="text" size="5" maxlength="5" decimals="2"> 
 
</form>

相反,如果你指的是自定義的數據屬性:

小數=」 2「

用戶輸入:123.456

輸入更改爲:123.46

你可以這樣做:

$(function() { 
 
    $('[data-decimals]').on('blur', function(e){ 
 
    var val = +$(this).data('decimals'); 
 

 
    var txtNumber = +this.value; 
 

 
    this.value = txtNumber.toFixed(2); 
 
    }); 
 
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
 

 
<form> 
 
    <input type="number" size="5" maxlength="5" data-decimals="2"> 
 
</form>

+0

因此,總而言之,沒有辦法無需在函數內部以某種方式詢問屬性值,也不需要快捷方式。我的問題主要是信息性的,希望能夠學習新的東西。謝謝。 –