简体   繁体   中英

How to execute <script> code in a javascript append

I'm working with a plugin that is only Javascript. I need to have it dynamically create a DIV element with an advertisement in it.

$(this).append('<div class="overlay-background">Advertisement

     <script type="text-javascript">

          GA_googleFillSlot("blog_landing_right_rectangle_300x250");

     </script>'

appending HTML into the DOM does not cause the browser to evaluate any script tags in said appended HTML.

eval($(this).find("script").text());

I know this is an old question but I've had a similar problem today. The solution was using createContextualFragment<\/a> .

var tagString = '<script async type="text/javascript" src="path_to_script"></script>';

var range = document.createRange();
range.selectNode(document.getElementsByTagName("BODY")[0]);
var documentFragment = range.createContextualFragment(tagString);
document.body.appendChild(documentFragment);

This code works in my browser.

$('body').append('<script>alert("test");<' + '/' + 'script>');

在您的情况下,一种解决方法可能是附加一个带有 onload 事件的假图像:

<img src="blank.gif" onload="GA_googleFillSlot('blog_landing_right_rectangle_300x250')" />

Please try:

s = '<' + 'script type="text-javascript">' +
    'GA_googleFillSlot("blog_landing_right_rectangle_300x250");' +
    '<' + '/' + 'script>';
$(this).append(s);

since your are in javascript, you can append and then execute the code:

$(this).append('<div class="overlay-background">Advertisement</div>');

GA_googleFillSlot("blog_landing_right_rectangle_300x250");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM