jquery replace不适用于单引号

时间:2011-12-02 21:50:37

标签: jquery jstl drop-down-menu

我试图在选择框中删除我的选项中的单引号,但下面的内容似乎不起作用:

$(function(){
  $("#agencyList").each(function() {
    $("option", $(this)).each(function(){
      var cleanValue = $(this).text();
      cleanValue.replace("'","");
      $(this).text(cleanValue);
    });
  });
});

它仍然有单引号。 select是使用JSTL forEach循环构建的。任何人都可以看到可能出现的问题吗?

1 个答案:

答案 0 :(得分:8)

您必须使用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,因为没有必要将this对象包装在jQuery对象中。
  • 您的代码可以进一步优化我的合并两个选择器:

    $(function(){
      $("#agencyList option").each(function() {
          var cleanValue = $(this).text();
          cleanValue = cleanValue.replace(/'/g,"");
          $(this).text(cleanValue);
      });
    });