我试图从选择框中的选项中删除单引号,但以下内容似乎不起作用:
$(function(){
$("#agencyList").each(function() {
$("option", $(this)).each(function(){
var cleanValue = $(this).text();
cleanValue.replace("'","");
$(this).text(cleanValue);
});
});
});
它仍然有单引号。该选择是使用 JSTL forEach 循环构建的。谁能看出可能出了什么问题吗?
最佳答案
您必须使用cleanValue = cleanValue.replace(...)
分配新值。另外,如果您想替换所有单引号,请使用全局正则表达式:/'/g
(替换所有出现的单引号):
$(function(){
$("#agencyList").each(function() {
$("option", this).each(function(){
var cleanValue = $(this).text();
cleanValue = cleanValue.replace(/'/g,"");
$(this).text(cleanValue);
});
});
});
另一个调整:
- 将
$(this)
替换为this
,因为无需将this
对象包装在 jQuery 对象中。 通过合并两个选择器,您的代码可以得到更多优化:
$(function(){ $("#agencyList option").each(function() { var cleanValue = $(this).text(); cleanValue = cleanValue.replace(/'/g,""); $(this).text(cleanValue); }); });
关于jquery 替换不适用于单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8363155/