Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

javascript - 可以使用innerHTML插入脚本吗?(Can scripts be inserted with innerHTML?)

I tried to load some scripts into a page using innerHTML on a <div> .

(我试图在<div>上使用innerHTML将一些脚本加载到页面中。)

It appears that the script loads into the DOM, but it is never executed (at least in Firefox and Chrome).

(脚本似乎已加载到DOM中,但从未执行(至少在Firefox和Chrome中)。)

Is there a way to have scripts execute when inserting them with innerHTML ?

(使用innerHTML插入脚本时,是否可以执行脚本?)

Sample code:

(样例代码:)

 <!DOCTYPE html> <html> <body onload="document.getElementById('loader').innerHTML = '<script>alert(\'hi\')<\/script>'"> Shouldn't an alert saying 'hi' appear? <div id="loader"></div> </body> </html> 

  ask by Craig translate from so


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a very interesting solution to your problem: http://24ways.org/2005/have-your-dom-and-script-it-too

(这是一个非常有趣的解决方案: http : //24ways.org/2005/have-your-dom-and-script-it-too)

So use this instead of script tags:

(因此,使用它代替脚本标签:)

<img src="empty.gif" onload="alert('test');this.parentNode.removeChild(this);" />


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...