给定代码行
var value = $("#text").val();
and value = 9.61,我需要将9.61转换为9:61。如何使用JavaScript替换函数在这里?
给定代码行
var value = $("#text").val();
and value = 9.61,我需要将9.61转换为9:61。如何使用JavaScript替换函数在这里?
当前回答
最优雅的方法可能是一步完成。看到瓦尔()。
$("#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(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(".", ":") );
$("#text").val(function(i,v) {
return v.replace(".", ":");
});
这可以用常规的JavaScript函数replace()来完成。
value.replace(".", ":");
这样做:
var value = $("#text").val(); // value = 9.61 use $("#text").text() if you are not on select box...
value = value.replace(".", ":"); // value = 9:61
// can then use it as
$("#anothertext").val(value);
更新到反映到当前版本的jQuery。这里也有很多答案最适合这种情况。作为开发人员,您需要知道哪个是哪个。
替换所有事件
要一次替换多个字符,可以使用如下的东西:name。替换(/ & / g,“-”)。这里我用-替换了所有&字符。G是全球的意思
注意-您可能需要添加方括号以避免错误-标题。替换(/[+]/g, " ")
归功于vissu和Dante Cullari