Javascript 使用document.write()将html写入iframe,但jquery在IE9中不起作用
我在本地系统中存储了一个html页面,我尝试获取内容,然后将其写入iframeJavascript 使用document.write()将html写入iframe,但jquery在IE9中不起作用,javascript,jquery,html,internet-explorer-9,Javascript,Jquery,Html,Internet Explorer 9,我在本地系统中存储了一个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"
<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,但错误脚本5009:“$”未定义在IE9中加载页面时会发生,但在google chrome和firefox中工作正常。问题可能是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>
代表问题作者发布解决方案
感谢拉尔夫·纳杰姆的回答,但我找到了另一种方法来解决这个问题,我觉得更合适
等待页面加载后再执行脚本。下面是一个例子:
<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>
有时$会出现问题。使用jQuery而不是jQuery cdn.Er时,“$”未定义当您单击按钮时会发生什么?这听起来很奇怪,因为处理程序中没有$,如果没有定义$,它应该在页面加载时抛出一个错误。尝试使用jQuery和jQuery cdn,问题没有解决。我更改了我的问题,页面加载时出错。谢谢你的回复。此方法解决了问题,但由于代码重复,代码将变长。您的意思是script.onreadystatechange和script.onload同时启动?是的,但不仅如此,此外,由于script.onreadystatechange和script.onload中的代码相同,代码将更长。确定,然后删除script.onreadystatechange,因为只需触发1个事件。onreadystatechange只是为了支持ie8和之前的版本,所以如果你不在乎的话,就不需要它。哇,它不总是在IE9或其他版本中阻塞吗?那太奇怪了!