jquery,属性选择器,获取当前属性值

jquery, attribute selector, get current attribute value

我有一个输入:

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

其中 "decimals" 可以是 0 到 4 之间的值。

在 onblur 事件中,用户输入的任何数字都将更改为符合要求,因此:

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

这很简单,没问题。我的问题是关于获取 "decimals." 值的最有效方法 通常,我会写 (jquery):

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

...但在我看来,应该有一种更有效的方法来获取 "decimals" 的值,因为我们已经根据该属性选择了输入。有没有,或者我的代码是唯一的写法吗?

你可以看看attributes. This is a 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>

相反,如果您指的是自定义数据属性:

decimals="2"

User enters: 123.456

Input is changed to: 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>