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

时间:2016-08-16 17:17:02

标签: javascript jquery attributes selector

我有一个输入:

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

其中“小数”可以是0到4之间的值。

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

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

这是微不足道的,没问题。我的问题是获得“小数”值的最有效方法。通常,我会写(jquery):

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

...但在我看来应该有一种更有效的方法来获得“小数”的值,因为我们已经根据该属性选择了输入。是否存在,或者我的代码是唯一的写法?

1 个答案:

答案 0 :(得分:0)

您可以查看attributes。这是NamedNodeMap,包含一些功能。

如果您指的是属性而不是custom data attributes,您可以这样做:

&#13;
&#13;
$(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');
});
&#13;
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<form>
    <input type="text" size="5" maxlength="5" decimals="2">
</form>
&#13;
&#13;
&#13;

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

  

小数=&#34; 2&#34;

     

用户输入:123.456

     

输入更改为:123.46

你可以这样做:

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

    var txtNumber = +this.value;

    this.value = txtNumber.toFixed(2);
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

相关问题