简体   繁体   中英

Javascript difference between document.write and DOM element.AppendChild(text)

I want to embed and show a flash file. It works fine with document.write but when I tried with AppendChild(text) it doesn't show flash but pure text instead. What DOM method to use instead ?

  <html>
  <head>
 <script>
  function addText(text,elementId){
    if (document.createTextNode){
      var mytextNode=document.createTextNode(text)
      document.getElementById(elementId).appendChild(mytextNode)
    }
  }

    </script>

  </head>

  <body>

                <div id="test">

                </div>

  <script>
      addText("<embed height='100' width='100' type='application/x-shockwave-flash' allowscriptaccess='always' wmode='transparent' quality='high' swliveconnect='true' name='test' id='test' src='test.swf'>",'test');
  </script>     
  </body></html>

Because you are creating a text node, not serialised HTML.

You could change the function to...

function addHTML(html, elementId) {
    if (document.createElement) {

        var holder = document.createElement('div');

        holder.innerHTML = html;

        var target = document.getElementById(elementId);

        while (holder.hasChildNodes()) {
            target.appendChild(holder.firstChild);
        }
    }
}

jsFiddle .

(function () {
    var myEmbed = document.createElement("embed");
    myEmbed.type="application/x-shockwave-flash";
    myEmbed.height='100';
    myEmbed.width='100';
    …
    document.getElementById("test").appendChild(myEmbed);
}());

At first glance such an approach can often seem unnecessarily noisy and worthless, but it integrates much more sanely with the natural syntax of HTML. If you want to be able to write HTML directly into your document, you might be happier with a framework like jQuery, which allows syntax like:

$("<embed src='…'/>")

However, if you're just doing all this to embed Flash, use swfobject .

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