3
Asp.Net 4.5(WebForm)如何從後面的代碼中調用IFrame中的JS函數
如何在代碼背後成功調用iframe中的js函數? 我正在使用RegisterClientScriptBlock來啓動JS功能aspx頁面,該頁面依次調用iframe的html頁面中的JS功能。
主頁面中的客戶端按鈕正常工作。 服務器按鈕不能按預期工作。但它確實可以識別iframe對象和contentWindow。
錯誤
- 類型錯誤:對象不支持屬性或方法 'TestFunc'
任何建設性幫助,將不勝感激。注意:這是一個簡明的例子。
MainPage.aspx
<head runat="server">
<title></title>
<script type="text/javascript">
function InvokeJS(param) {
var iframe = document.getElementById("MyIFrame");
try {
iframe.contentWindow.TestFunc(param);
//=============================================================
//Would really like to use the .apply method over calling the
//function directly. This does work in pure HTML, but not aspx
//=============================================================
//var _ARGS = [];
//_ARGS.push(param);
//iframe.contentWindow('TestFunc').apply(null, _ARGS);
} catch (e) {
alert(e);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="ServerButton" runat="server" Text="Server" />
<input id="ClientButton" type="button" value="Client" onclick="InvokeJS('From Client');" />
<br />
<br />
<iframe id="MyIFrame" runat="server" src="Pages/Test.html" style="width: 700px; height: 300px;"></iframe>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
MainPage.aspx(代碼隱藏)
Protected Sub ServerButton_Click(sender As Object, e As EventArgs) Handles ServerButton.Click
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType, "InvokeJS", "InvokeJS('From Server');", True)
End Sub
的test.html(加載到IFRAME)
<head>
<title>Test</title>
<script type="text/javascript">
function TestFunc(param) {
document.getElementById("DisplayParam").innerHTML = param;
}
</script>
</head>
<body>
<h1>HTML Page</h1>
<h2 id="DisplayParam"></h2>
</body>
</html>
按鈕後被按下,查看源代碼是什麼樣的?如果將ClientScriptBlock直接放入OnLoad中,會發生什麼?它會執行嗎?在瀏覽器中調試時是否有任何JS錯誤? –
@the_lotus錯誤已添加到問題中,我添加了ClientScriptBlock window.onload = TestFunc;仍然無法正常工作,並且我可以看到在視圖源中更改的是requestId – TroyS