简体   繁体   English

使用document.write()将html写入iframe,但是jquery在IE9中不起作用

[英]use document.write() to write html in to iframe, but jquery not working in IE9

I have stored a html page in local system, and i try to get the contents then write to an iframe. 我已经在本地系统中存储了一个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>

i use document.write() to write the html code to the iframe, but error SCRIPT5009: '$' is undefined occur when page load in IE9, but work fine in google chrome & firefox. 我使用document.write()将html代码写入iframe,但是在IE9中加载页面时出现错误SCRIPT5009:'$'未定义 ,但在谷歌浏览器和Firefox中可以正常工作。

The issue might be that IE is executing the JS code before loading in jquery, try loading it in dynamically and listening for onload: 问题可能是IE在加载jquery之前正在执行JS代码,尝试动态加载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>

(Posted solution on behalf of the question author) . (代表问题作者发布解决方案)

Thank for Ralph Najm's answer, but I have found another method to solve this problem that I feel is more appropriate. 感谢拉尔夫·纳伊姆(Ralph Najm)的回答,但我发现了另一种解决此问题的方法,我认为这种方法更合适。

Wait until the page loaded before execute the script. 等待页面加载完毕,然后再执行脚本。 Below is the example: 下面是示例:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM