IE8中的javascript怪异,document.write问题

时间:2012-05-04 08:52:36

标签: javascript onclick document.write

任何想法为什么以这种方式添加谷歌加代码不会在IE8或任何其他版本中工作我猜?虽然在Firefox中运行得很好。

现场演示:http://jsfiddle.net/9zqsZ/

<script>

var socialString = '<g:plusone size="tall"></g:plusone>';
document.write(socialString);

   //google plus share button
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();

</script>

我只是想把它放在外部文件中。奇怪的是它只是不能与document.write一起使用,如果直接放在html中就可以工作。在这种情况下如何实现它?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

<script>
    if (navigator.appVersion.indexOf("MSIE") != -1) {
      var socialString = '<g:plusone size="tall"></g:plusone>';
      var newEle = document.createElement(socialString);
      document.body.appendChild(newEle);
    }
    else {
       var socialString = '<g:plusone size="tall"></g:plusone>';
       document.write(socialString);
    }

   //google plus share button
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>