gpt4 book ai didi

javascript - 如何从代码隐藏中调用 IFrame 中的 JS 函数

转载 作者:行者123 更新时间:2023-12-01 01:43:30 26 4
gpt4 key购买 nike

Asp.Net 4.5(WebForm)

如何从代码隐藏中成功调用 Iframe 中的 js 函数?我正在使用 RegisterClientScriptBlock 来触发 aspx 页面中的 JS 函数,该函数又调用 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>

最佳答案

window.onload = TestFunc();不起作用,因为 Test.html 在 onload 事件引发之前实际上没有完全加载,这与 ServerButton 相同,因为脚本 block 是在 test.html 加载之前注册的。这就是为什么没有 TestFunc 无法调用的原因。

你可以试试

<asp:Button ID="ServerButton" runat="server" Text="Server" OnClientClick="InvokeJS('From Server');" />

如果您希望它在运行脚本之前执行某些操作,我认为您不喜欢它

那就玩这个把戏

 <script type="text/javascript">
//this is help check if postback by Server Button, if yes then invoke
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) {
if (args._postBackElement.id == '<%=ServerButton.ClientID%>')
$('#MyIFrame').load(function(){
InvokeJS('From Client');
console.log('load the iframe');
});


}

</script>

关于javascript - 如何从代码隐藏中调用 IFrame 中的 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32739763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com