搜索&用jQuery替换整个HTML字符串

时间:2012-09-02 04:58:40

标签: javascript jquery

我在搜索时遇到了一些麻烦替换整个HTML字符串。

我在这个小提琴中的例子是我试图用它的所有类替换整个div标签。标记:

http://jsfiddle.net/LqkNE/

正如你所看到的,有两个小问题 - 一个带有&符号的问题也引起了我的问题。

有人可以帮我解决我做错的事吗?

2 个答案:

答案 0 :(得分:1)

这是一个有效的版本:http://jsfiddle.net/Regisc/jeVjn/

如上所述,&需要进行编码,对于第一个问题,您只能替换强部分,因为其余部分不会更改

编辑:

// Issue #1: This is my failed attempt to search & replace a large portion of the string:

jQuery(document).ready(function () {
  function changeString() {
    jQuery(".flex-caption").parent().html(function (i, str) {
      return str.replace(
        '<div class="flex-caption"><strong>Reach for the Clouds with Simple Solutions</strong>&nbsp;</div>', 
        "<div class='flex-caption flex-align'><strong><div class='caption-align caption-right'>REPLACED TEXT! Reach for the Clouds with Simple Solutions</div></strong>&nbsp;</div>"
      );
    });
  }

  changeString();
});

http://jsfiddle.net/jeVjn/1/

请注意parent(),简单引用和&nbsp;这不起作用,因为.flex-caption html为<strong>...而非<div class=".flex-caption">...

答案 1 :(得分:0)

&需要编码为&amp;

所以html应该是:

      <li><div class="flex-caption"><strong>Obtain the Courage to Suceed as a Leader, Team, &amp; Company</strong>&nbsp;</div></li>

JavaScript:

jQuery(document).ready(function(){
  function changeString2 () {
    jQuery(".flex-caption").html(function(i, str) {
      return str.replace("<strong>Obtain the Courage to Suceed as a Leader, Team, &amp; Company", "<i>Obtain the Courage to Suceed as a Leader, Team, &amp; Company");
    });
  }
  changeString2();
});