迭代p标签中的文本会杀死p标签中的所有html

时间:2011-03-11 17:02:10

标签: jquery

我正在使用这个jquery代码来查看

标签,并用围绕它的span标签替换word图像。问题是我的代码正在杀死<p>标记中的任何其他html。

这是我的代码

$('p').each(
   function() {
       var text = $(this).text();
       var spanText = text.replace('image', '<span class="bText">image</span>');
       $(this).html(spanText);
   }
);

这是应用之前的html

<p>
I have an image.
<br>
There is a link <a target="_blank" href="https://mysite.com">mylink</a>
     </p> 

在jquery之后

<p>I have an <span class="bText">image</span>. There is a link mylink </p>

2 个答案:

答案 0 :(得分:4)

改为使用html() [docs]

var text = $(this).html();

text() [docs],顾名思义,只获取文本内容,没有HTML标记。

更多信息:

如果将字符串传递给replace [docs],则只会替换该字符串的第一个匹配项。如果您要替换所有匹配项,则需要regular expression [docs] g标志。


您的代码可以缩短为(需要jQuery 1.4):

$('p').html(function(i, html) {
    return html.replace(/image/g, '<span class="bText">image</span>');
    // or /\bimage\b/g if you e.g. don't want to match `preimage`
});

答案 1 :(得分:0)

//mine from scratch - works in chrome, ie, and firefox
$("p").each(function(){
    var html = $(this).html();
    var newHtml = html.replace("image","<span style='font-weight:bold;'>image</span>");
    $(this).html(newHtml);
});
//end

代码更改

var text = $(this).text();

var text = $(this).html();

希望这会有所帮助。