我有一个输入:
<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 ***
});
...但在我看来应该有一种更有效的方法来获取“小数”的值,因为我们已经根据该属性选择了输入。有没有,或者我的代码是唯一的写法吗?
最佳答案
您可以查看 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>
如果您指的是自定义数据属性:
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>
关于javascript - jquery,属性选择器,获取当前属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38980850/