使用函数格式化值并像这样调用:
$(".vlrTotal").val(formatReal(formatarValor($(".vlrTotal").val())));
我的 HTML:
<td>
<input readonly type="text" name="vlrTotal[]" value="<?php echo $item['VwEstPedOnlineItens']['vlr_custo_total']; ?>" class="vlrTotal" style="width: 100%;"/>
</td>
结果如上图所示。
现在如果我取消格式化该值的功能,结果是这样的:
问题是,在格式化值后,所有输入 (".vlrTotal")
显示相同的值(第一个),但是当我检查元素时,该值显示正确的值。如果我取消格式化该值的功能,它就会“起作用”。
我不知道该怎么办了。
PS:控制台.log:
input.vlrTotal property value = "7.199,28" attribute value = "2799.72"
input.vlrTotal property value = "7.199,28" attribute value = "2399.76"
最佳答案
由于您有多个带有 $(".vlrTotal")
的元素,因此您需要迭代并为每个元素设置值。当您访问 .val()
方法时,它会按照您的体验获取第一个元素的值。
您需要使用.val( function )
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
使用
$(".vlrTotal").val(function(_, value){
return formatReal(formatarValor(value));
});
OR,简单的$.fn.each()
$(".vlrTotal").each(function(){
$(this).val(formatReal(formatarValor($(this).val())));
});
注意:假设您已定义具有所需行为的 formatReal
和 formatarValor
函数。
关于javascript - 将值格式化为 "doesn' t work',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29969271/