用javascript替换html部分

时间:2014-01-04 08:04:31

标签: javascript jquery html

我遇到问题:我需要用必要的html替换页面上的一些单词。例如:

t = $('body').html();
t = t.replace(/Myword/g, '<div></div>');
$('body').html(t);

它正在成功运作。但是......如果body包含javascript标签 - JS再次运行。

如果我使用document.body - 它正在工作

t = document.body.innerHTML;
t = t.replace(/Myword/g, '<div></div>');
document.body.innerHTML = t;

但我对jQuery解决方案感兴趣。也许你有它?

提前致谢

4 个答案:

答案 0 :(得分:3)

一个简单的解决方案是忽略所有脚本标记。

t = $('body').clone().find("script").remove().end().html();
t = t.replace(/Myword/g, '<div></div>');
$('body').html(t);

Demo

答案 1 :(得分:1)

This solution might help you.

如果出现以下情况,则不会执行JavaScript:

  1. <script type=”text/xml”>内的JavaScript未执行
  2. <script type=”text/xml” type=”text/javascript”>内的JavaScript也没有执行,因为只考虑第一种类型
  3. 所以更改类型:

    function preventJS(html) {
         return html.replace(/<script(?=(\s|>))/i, '<script type="text/xml" ');
    }
    

    并使用它:

    t = $('body').html();
    t = t.replace(/Myword/g, '<div></div>');
    $('body').html(preventJS(t));
    

答案 2 :(得分:1)

正如Arun在评论中提到的那样,你应该更具体地定位元素。如果您使用JQuery获取整个<script>内容然后重新插入它,则会重新评估<body>标记。尝试在<div>

中包装所需的内容
<body>
    <div id="wrapper">
        <p>Text that will be altered</p>
    </div>
    <script type="text/javascript">
        //javascript code
    </script>
</body>

然后您的代码将替换文本:

t = $('#wrapper').html();
t = t.replace(/Myword/g, '<div></div>');
$('#wrapper').html(t);

答案 3 :(得分:1)

更好的方法是在最具体的元素中替换"Myword"。这只会替换包含它的textNodes中的Myword,而不是其他地方。

var each = Array.prototype.forEach;

var $myword = $(":contains('Myword')");
$myword.each(function() {
    each.call(this.childNodes, function(ele) {
        if(ele.nodeType === 3 && ele.nodeValue.indexOf('Myword') >= 0) {//if ele is a text node and contains myword
            ele.nodeValue = ele.nodeValue.replace(/Myword/g, "some text");
        } 
    }, this);
});

尝试在此页面上运行