[英]How to display javascript ad unit inside an article by using insertAdjacentHTML method
I am trying to call a google ad sense code inside an article, But i don't want to past ad sense code in middle of an article. 我正在尝试在文章内调用Google广告代码,但是我不想在文章中间插入广告代码。 For that i am trying some thing like bellow, but it is not working as i expected because of java script issues. 为此,我正在尝试像波纹管一样的东西,但是由于Java脚本问题,它无法按我的预期工作。
<script> var x = document.getElementById("myArticle").querySelectorAll("p"); x[1].insertAdjacentHTML('beforeBegin', '<script>document.write(2+1)</script>' ); </script>
<div id="myArticle"> <p>A heading with class="example" in div</p> <p>A paragraph with class="example" in div.</p> <p>A paragraph with class="example" in div.</p> </div>
The problem is that the </script>
inside your string terminates the script. 问题在于字符串中的</script>
终止脚本。
You can use something like "</sc" + "ript>"
or "<\\/script>"
to prevent this. 您可以使用"</sc" + "ript>"
或"<\\/script>"
来防止这种情况。
var x = document.getElementById("myArticle").querySelectorAll("p"); x[1].insertAdjacentHTML('beforeBegin', '<script>document.write(2+1)<\\/script>' );
<div id="myArticle"> <p>A heading with class="example" in div</p> <p>A paragraph with class="example" in div.</p> <p>A paragraph with class="example" in div.</p> </div>
Note that the script in script
elements inserted like this won't run automatically. 请注意,这样插入的script
元素中的script
不会自动运行。 If you want to run some string, you can use eval
. 如果要运行一些字符串,可以使用eval
。 Use it carefully. 小心使用。
eval('document.write(2+1)');
<div id="myArticle"> <p>A heading with class="example" in div</p> <p>A paragraph with class="example" in div.</p> <p>A paragraph with class="example" in div.</p> </div>
You shouldn't use document.write
, though. 不过,您不应该使用document.write
。 See the warning in the spec . 请参阅规范中的警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.