【问题标题】:use document.write() to write html in to iframe, but jquery not working in IE9使用 document.write() 将 html 写入 iframe,但 jquery 在 IE9 中不起作用
【发布时间】:2018-10-27 06:50:20
【问题描述】:

我在本地系统中存储了一个 html 页面,我尝试获取内容然后写入 iframe。

<html>
<head>
    <title></title>
    <script src="js/jquery.min.js" type="text/javascript"></script>
    <link href="styles/myStlye.css" rel="stylesheet" type="text/css" />
</head>
<body><button id="buttonClick">Click Me</button></body>
<script>
    $(document).ready(function(){
        $("#buttonClick").click(function(){
            alert("Button clicked.");
        });
    });
</script>
</html>

我使用 document.write() 将 html 代码写入 iframe,但在 IE9 中加载页面时出现错误 SCRIPT5009: '$' is undefined,但在 google chrome 和 firefox 中工作正常.

【问题讨论】:

  • 有时$会出现问题。改用 jQuery
  • 试试 jquery cdn。
  • 呃,'$' is undefined 发生在当您单击按钮时?这听起来很奇怪,因为处理程序中没有$,如果没有定义$,它应该在页面加载时抛出错误。
  • 尝试使用jQuery和jquery cdn,问题没有解决。我改变了我的问题,页面加载时出现错误。

标签: javascript jquery html internet-explorer-9


【解决方案1】:

问题可能是IE在加载jquery之前正在执行JS代码,尝试动态加载并监听onload:

<html>

<head>
  <title></title>
  <link href="styles/myStlye.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <button id="buttonClick">Click Me</button>
  <script>
    var script = document.createElement("script");

    script.src = "js/jquery.min.js";

    script.onreadystatechange = function () {
      if (this.readyState == 'complete' || this.readyState == 'loaded') {
        $("#buttonClick").click(function () {
          alert("Button clicked.");
        });
      }
    };
    script.onload = function () {
      $("#buttonClick").click(function () {
        alert("Button clicked.");
      });
    };
    document.querySelector('body').appendChild(script);
  </script>
</body>

</html>

【讨论】:

  • 感谢您的回复。这种方法解决了问题,但是由于代码重复,代码会比较长。
  • 你的意思是 script.onreadystatechange 和 script.onload 都在触发?
  • 是的,不仅如此,由于script.onreadystatechange和script.onload中的代码相同,因此代码会更长。
  • OK 然后删除 script.onreadystatechange 因为您只需要触发 1 个事件。 onreadystatechange 仅用于支持 ie8 及之前的版本,因此如果您不关心它,则不需要它。
  • 哇,&lt;script&gt;s 不总是在 IE9 中阻塞吗?这很奇特!
【解决方案2】:

(代表问题作者发布解决方案)

感谢 Ralph Najm 的回答,但我找到了另一种我觉得更合适的方法来解决这个问题。

等到页面加载完毕后再执行脚本。下面是例子:

<html>
<head>
    <title></title>
    <script src="js/jquery.min.js" type="text/javascript"></script>
    <link href="styles/myStlye.css" rel="stylesheet" type="text/css" />
</head>
<body><button id="buttonClick">Click Me</button></body>
<script>
    window.addEventListener('load', function() {
        $(document).ready(function(){
            $("#buttonClick").click(function(){
                alert("Button clicked.");
            });
        });
    });
</script>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多