在键入jQuery时用逗号替换逗号

lui*_*imo 1 html javascript jquery jquery-plugins

您好我想使用jQuery键入文本输入字段时用点替换逗号.我现在有这个代码;

$(document).on('change', '.unitprice', function() {
  $(this).val().replace(/,/g, '.');
});
Run Code Online (Sandbox Code Playgroud)

输入字段的类是unitprice

但它不起作用..我似乎无法在谷歌上找到正确的答案.有人知道如何实现这个目标吗?

Laz*_*vić 8

你只是改变变量而不是回写它.

$(this).val($(this).val().replace(/,/g, '.'));
Run Code Online (Sandbox Code Playgroud)

  • Upvoted是因为你是对的,但我建议:`$(this).val(function(index,currentValue){return currentValue.replace(/,/ g,'.');});`而不是使用`$(this).val()`两次(不必要).或者,为简洁起见:`this.value = this.value.replace(...);` (3认同)