innerHTML中载入js的方法

本文介绍了一种解决Safari浏览器中通过AJAX动态加载的脚本无法执行的问题的方法。作者最初尝试使用<script>标签插入DOM,但发现Safari无法执行这些脚本。最终通过将<script>标签替换为<div>标签,并利用jQuery和eval()函数手动执行脚本解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A common AJAX technique is to return straight HTML and use the innerHTML element attribute to insert it into the DOM. Unfortunately, JavaScript inserted into the DOM this way (inside a <script> tag) will not execute in all browsers.

I found this out when trying to implement a dynamically changing PlotKit graph on my companies intranet site. It worked in Firefox (of course) and IE was coaxed into working be using the DEFER attribute . But the best Safari could do was leave a big blank space where my beautiful graph should be. Even though there was probably only one other employee that used Safari, I knew there was no way this was going to stand. There must be a solution, right?

Some googling turned up this posting , where the problem was solved using a combination of cloneNode(), innerHTML and appendChild(). Fancy. It works with Opera and IE, but not with Safari .

Then, my eureka moment came. I replaced the <script> tag in the RPC with a <div class=”javacript”> tag, still keeping all the script inside the <div>. Next, I added .javascript { display: none; } to the style sheet and did some jQuery magic:

$('#ajaxLoading').ajaxStop(function() {
$('.javascript').each(function() {
eval($(this).text());
});
});

This simple function runs every time an AJAX call is completed and uses eval() to manually run the JavaScript. It’s ugly, it’s probably violating some sort of standard, but guess what? It works in Safari .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值