Let script scripts in innerHTML Execute

Source: Internet
Author: User
Script | execution

When we use Ajax, we often use the innethtml to update the content of the object, but for the updated <script> script browser is not able to execute, I am in front of Ajax beginners often encounter problems answer This article has mentioned this issue, It was not executed because the:<script> tag was parsed only in the first time the browser was loaded, and here's how to get <script> running.

Analyze problems

Since <script> is only parsed in document loading, I have to call the document.write () method to reload once, but in this case the contents of the original page will be overwritten, so we have to use the IFRAME to document.write ( ) load up.

Solve the problem

var jscode = need to execute the JS code var jsiframe = document.createelement ("iframe"); JsIframe.style.display = "none";//Hide Jsiframe document.body.appendChild (jsiframe); With (Window.frames[window.frames.length-1]) {  document.open ();  document.write (Jscode); Execute JS code  document.close ();} document.body.removeChild (Jsiframe);//delete iframe object after execution

Here is a problem to note, because Jscode is run in the IFRAME, so all page elements are under the IFRAME parent object, to call the page element object must be parent.obj this way.

Another method:

Dynamically create a script object with Dom
var script=document.createelement ("script");
Script.src= "Xxxx.js";
Document.body.appendChild (script);



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.