用javascript替换html部分 [英] Replace html part by javascript

查看:73
本文介绍了用javascript替换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解决方案感兴趣。也许你有吗?



提前致谢

解决方案

解决方法是忽略所有脚本标记。

  t = $('body')。clone()。find(脚本)除去()()结尾的HTML()。; 
t = t.replace(/ Myword / g,'< div>< / div>');
$('body')。html(t);

演示


I have problem: I need to replace some word on page with needed html. For example:

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

It is working successfully. But... If body contains javascript tag - JS running again.

If I use document.body - it working

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

But I am interested in jQuery solution. Maybe you have it?

Thanks in advance

解决方案

A simple solution would be to ignore all the script tags.

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

Demo

这篇关于用javascript替换html部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆