我试图从选择框中的选项中去掉单引号,但下面的代码似乎不起作用:
$(function(){
$("#agencyList").each(function() {
$("option", $(this)).each(function(){
var cleanValue = $(this).text();
cleanValue.replace("'","");
$(this).text(cleanValue);
});
});
});
仍然有单引号。选择是用JSTL forEach循环构建的。有人能看出哪里出了问题吗?
您必须使用cleanValue = cleanValue.replace(...)
来分配新值。此外,如果您想替换所有单引号,请使用全局RegEx: /'/g
(它替换所有出现的单引号):
$(function(){
$("#agencyList").each(function() {
$("option", this).each(function(){
var cleanValue = $(this).text();
cleanValue = cleanValue.replace(/'/g,"");
$(this).text(cleanValue);
});
});
});
另一个调整:
- 将
$(this)
替换为this
,因为没有必要在jQuery对象中包装this
对象。 你的代码可以通过合并两个选择器来优化:
$(function(){ $("#agencyList option").each(function() { var cleanValue = $(this).text(); cleanValue = cleanValue.replace(/'/g,""); $(this).text(cleanValue); }); });