给定代码行

var value = $("#text").val();

and value = 9.61,我需要将9.61转换为9:61。如何使用JavaScript替换函数在这里?


当前回答

$("#text").val(function(i,v) { 
   return v.replace(".", ":"); 
});

其他回答

这可以用常规的JavaScript函数replace()来完成。

value.replace(".", ":");
$("#text").val(function(i,v) { 
   return v.replace(".", ":"); 
});

最优雅的方法可能是一步完成。看到瓦尔()。

$("#text").val(function(i, val) {
  return val.replace('.', ':');
});

相比:

var val = $("#text").val();
$("#text").val(val.replace('.', ':'));

从文档中可以看出:

.val( function(index, value) ) function(index, value)A function returning the value to set. This method is typically used to set the values of form fields. For <select multiple="multiple"> elements, multiple s can be selected by passing in an array. The .val() method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value: $('input:text.items').val(function(index, value) { return value + ' ' + this.className; }); This example appends the string " items" to the text inputs' values.

这需要jQuery 1.4+。

简单的一句话:

$("#text").val( $("#text").val().replace(".", ":") );

我喜欢jQuery的方法链接。简单地做……

    var value = $("#text").val().replace('.',':');

    //Or if you want to return the value:
    return $("#text").val().replace('.',':');