`
jarod2008
  • 浏览: 80731 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

innerHTML中载入js的方法

阅读更多

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 .

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics