0

我试图将 html 从第 2 页加载到第 1 页,但它的 JavaScript 不起作用,这是同源策略吗?如果是我如何绕过这个?

第 1 页:

    <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>page 1 test</title>
<script src="js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#thisandthat').click(function() {
    $("#hide").toggle('fast');
    $("#cont").load('testpage2.html #res')
     $("#unhide").toggle('fast');
     console.log ()
});
});
</script>
</head>

<body>
<div id="">
<input id="thisandthat" name="test but" type="button" value="Button" />
<div id="hide" style="background-color:#050; width:100; height:100;">this and other things</div>
</div>
<div id="cont">
</div>
</body>
</html>

第2页

    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>page 1 test</title>
<script src="js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#thisand').click(function() {
    $("#unhide").toggle('fast');
    alert ('im in')
});
});
</script>
</head>

<body>
<div id="res">
<input id="thisand" name="test but" type="button" value="Button" />
<div id="unhide" hidden="" style="background-color:#09F; width:100; height:100;">i     apppear</div>
</div>

</body>
</html>

如您所见,page2 所需的 javascript 存在于 page1 上。请帮忙。

4

1 回答 1

1

问题是您在您的$("#cont").load('testpage2.html #res')

jQuery 只会加载第 2 页的那部分,因此不会加载 Javascript。如果您删除 id 选择器,它将加载整个页面,包括 Javascript。

$("#cont").load('testpage2.html')

或者,您可以将 Javascript 放在resdiv 中,这样就可以了。

附带说明一下,您的代码中缺少各种行尾分号,这不好。

于 2013-11-05T15:12:31.080 回答