Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
762 views
in Technique[技术] by (71.8m points)

add javascript into a html page with jquery

I want to add a javascript google ad but I can't insert the javascript into the div using jquery. I try to simulate my problem with this test, which is using some advice I found on stackoverflow , but it does not work.

I want <script type='text/javascript'>document.write('hello world');</script> to be inserted in the div, and "hello world" be displayed between the tag_1 and tag_2.

Here is the code :

<html>
    <head>
      <script type="text/javascript" src="jquery.js"></script>
      <script type="text/javascript">
         $(document).ready(function() {
         var str="<script type='text/javascript'>document.write('hello world');";
         str+="<";
         str+="/script>";

         $('#insert_here').append(str);
         });
      </script>
    </head>
    <body>
      tag_1<br/>
      <div id="insert_here">
      </div>
      tag_2<br/>
    </body>
</html>

Tanks for your answers,

Lucas

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See my answer to Are dynamically inserted <script> tags meant to work? for why you can't use innerHTML, which jQuery's functions map to when passed a HTML string, to insert a script element. document.write will also fail when used after the document has been fully parsed.

To work around this, you will have to use DOM functions to insert an element into the div. Google ads are iframes, so it's usually a case of finding the iframe code and appending that instead.


To correctly insert a script element, you need to use DOM functions, for instance:
var txt = 'alert("Hello");';
var scr = document.createElement("script");
scr.type= "text/javascript";

// We have to use .text for IE, .textContent for standards compliance.
if ("textContent" in scr)
    scr.textContent = txt;
else
    scr.text = txt;

// Finally, insert the script element into the div
document.getElementById("insert_here").appendChild(scr);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...