【问题标题】:jQuery - replace a word in text with a variable valuejQuery - 用变量值替换文本中的单词
【发布时间】:2011-11-30 18:12:05
【问题描述】:

我能弄清楚如何使用 jQuery 替换是将特定文本替换为特定文本。 不幸的是,我无法使用变量来做到这一点。

这是我正在尝试做的一个例子:

$("#id").html($("#id").html().replace(/myVariableHere/g, 'hello')); 

myVariableHere - 这是我要放置变量的地方。如果我在那里硬编码文本,一切正常。但是由于这个值是动态的(取决于你点击的内容),我必须在那里放一个变量,而不是一个硬编码的词...... 我的语法有什么问题?

提前致谢! :)

【问题讨论】:

  • 其实replace()跟jQuery没有关系,是纯javascript,不过还是个很好的问题

标签: jquery replace innerhtml


【解决方案1】:

RegExp 对象而不是文字形式:

var patt=new RegExp(myVariableHere,'g');
$("#id").html($("#id").html().replace(patt, 'hello')); 

【讨论】:

    【解决方案2】:

    为什么要使用正则表达式?

    $("#id").html($("#id").html().replace(myVariableHere, 'hello'));
    

    【讨论】:

      【解决方案3】:

      请注意,当您对元素的 HTML 内容(这是 .html() 返回/设置的内容)进行替换时,您实际上是在替换 HTML 代码,包括标签名称、类等。所以,如果您要替换的文本恰好是 HTML 标记或类名,您可能会破坏文档。为避免这种情况,遍历父元素的子节点,只在文本节点上进行替换:

      function replaceText($elem, text, replacement) {
          // Check if the element has just one child, and the child is a text node
          if ($elem[0].childNodes.length == 1 && $elem[0].firstChild.nodeType == 3)
              $elem.text($elem.text().replace(text, replacement));
          else
              // Call the replacement function on each child element
              $elem.children().each(function () {
                  replaceText($(this), text, replacement);
              });
      }
      

      【讨论】:

        【解决方案4】:

        我用了下面的sn-p

        $(this).text($(this).text().replace(old_word, new_word));
        

        $(this) 是包含要替换的文本的对象

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-05
          • 2018-07-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多