jquery 替换不适用于单引号

标签 jquery jstl drop-down-menu

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

$(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/

相关文章:

asp.net - 下拉条件列表项 ASP VB

php - Html Select Box 从mysql获取值

javascript - jquery 改变标签

php - 通过 twitter iframe 拦截对 twitter 按钮的点击,以通过 jquery 进行内部计数器

java - Apache Tomcat JSP 应用程序的一般强化技巧

jsp - 不能在jsp中使用jSTL

javascript - 清除 uikit html 编辑器

javascript - jQuery:禁用另一个函数的操作

java - JSTL - 如何解析输入日期

javascript - 打开时向上滑动的下拉子菜单