简体   繁体   English

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

[英]jquery, attribute selector, get current attribute value

I have an input: 我有一个输入:

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

where "decimals" could be a value from 0 to 4. 其中“小数”可以是0到4之间的值。

In the onblur event, whatever number the user types in will be changed to conform, thus: 在onblur事件中,用户键入的任何数字都将更改为符合,因此:

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

That's trivial, no problem. 这是微不足道的,没问题。 My question is about the most efficient way to get the value of "decimals." 我的问题是获得“小数”值的最有效方法。 Ordinarily, I'd write (jquery): 通常,我会写(jquery):

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

...but it seems to me there ought to be a more efficient way to get the value of "decimals" since we've already selected the input based on that attribute. ...但在我看来应该有一种更有效的方法来获取“小数”的值,因为我们已经根据该属性选择了输入。 Is there, or is my code as written the only way? 有没有,或者我的代码是唯一的写法?

You may take a look to attributes . 您可以查看属性 This is a NamedNodeMap with some functions. 这是一个带有一些函数的NamedNodeMap

If you are referring to attributes and not to custom data attributes you can do: 如果您要引用属性而不是自定义数据属性 ,则可以执行以下操作:

 $(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> 

Instead if you are referring to custom data attributes: 相反,如果您指的是自定义数据属性:

decimals="2" 小数= “2”

User enters: 123.456 用户输入:123.456

Input is changed to: 123.46 输入更改为:123.46

You can do: 你可以做:

 $(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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM