How to execute [removed] code in a javascript appe

2019-01-15 08:59发布

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.

I can't figure out why this doesn't work:

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

     <script type="text-javascript">

          GA_googleFillSlot("blog_landing_right_rectangle_300x250");

     </script>'

It results in the element created with "Hello World" but it does not execute the GA-googleFillSlot function.

4条回答
beautiful°
2楼-- · 2019-01-15 09:16

One workaround in your case could be to append a fake image with an onload event:

<img src="blank.gif" onload="GA_googleFillSlot('blog_landing_right_rectangle_300x250')" />
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-15 09:17

Please try:

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

UPD: alas, this won't work, please use wless1's solution instead

查看更多
beautiful°
4楼-- · 2019-01-15 09:32

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

If you really wanted to, you could evaluate the javascript by using eval():

eval($(this).find("script").text());
查看更多
在下西门庆
5楼-- · 2019-01-15 09:37

This code works in my browser.

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

so it might be that $(this) is what is actually causing your problem.

Can you replace it with 'body' and see if it works like that?

查看更多
登录 后发表回答