我有一個帶有iframe和按鈕的html文件,有沒有方法在點擊按鈕後在iframe正文中添加javascript函數?這是我的代碼。謝謝如何在iframe正文中添加javascript函數
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
function callMe() {
var frame = $('iframe'),
contents = frame.contents(),
body = contents.find('body');
var script2 = document.createElement("script");
script2.type = "text/javascript";
script2.text = " function setEmployeeId(){var employeeId = 0;};"
$(body).append(script2);
};
</script>
<title>sample</title>
</head>
<body>
<iframe src="page2.html">
</iframe>
<button onClick="callMe();">click</button>
</body>
</html>
我想要的結果就是這樣。
<html>
<head>
<title>sample</title>
</head>
<body>
<iframe>
<html>
<head>
<title></title>
</head>
<body>
<script>
function setemployeeId() {
var employeeId = 0;
};
</script>
</body>
</html>
</iframe>
</body>
</html>
該框架的頁面是否在您的域上? –
@AndrewBarber我會假設所以考慮到'src'是相對的「page2.html」。 – zamnuts
你可以在這裏找到你的答案... http://stackoverflow.com/questions/1591135/why-does-appending-a-script-to-a-dynamically-created-iframe-seem-to-run- – gts101