Loading JavaScript Into Div Dynamically

前端 未结 6 1207
难免孤独
难免孤独 2021-01-22 15:32

I need to load JavaScript code (which I don\'t have control over) from a URL into a div. The JavaScript code is a bunch of document.write() statements. Once the document.write()

6条回答
  •  渐次进展
    2021-01-22 16:00

    You can setup an html page that has just this (in this example it's called test2.html):

    
    

    You can then load this page into the DOM in an iframe and attach a load event handler that gets the contents of the page after it's done loading. This example then also removes the ').children('iframe').on('load', function () { //set the html of the `mydiv` element to the body of the loaded page (test2.html) $('#mydiv').html($(this).contents().children().children('body').html()); //remove the iframe from the DOM $(this).remove(); //set the source of the iframe after the `load` event handler is setup to make sure it fires properly }).attr('src', 'test2.html'); });

    Here is a demo: http://apexeleven.com/stackoverflow/document.write/test.html

    Note that .on() is new in jQuery 1.7 and is the same as .bind() in this case.

提交回复
热议问题