繁体   English   中英

用javascript替换html部分

[英]Replace html part by javascript

我有问题:我需要用必要的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解决方案感兴趣。 也许你有它?

提前致谢

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

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

演示

此解决方案可能对您有所帮

如果以下情况不执行JavaScript

  1. <script type=”text/xml”>中的JavaScript不会执行
  2. <script type=”text/xml” type=”text/javascript”>中的<script type=”text/xml” type=”text/javascript”>也不会执行,因为只考虑第一种类型

所以改变类型:

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));

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

更好的方法是在最具体的元素中替换"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);
});

尝试在此页面上运行它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM