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

时间:2015-09-23 12:33:42

标签: javascript jquery asp.net vb.net iframe

Asp.Net 4.5(WebForm)

如何成功从代码中调用iframe中的js函数? 我正在使用RegisterClientScriptBlock在 aspx 页面中激活JS函数,该页面又调用iframe的 html 页面中的JS函数。

主页面中的客户端按钮工作正常。 服务器按钮无法按预期工作。但它确实识别iframe对象和contentWindow。

错误

  • TypeError:对象不支持属性或方法' 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(CodeBehind)

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>

1 个答案:

答案 0 :(得分:0)

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

你可以尝试

library(data.table)
dt1 <- data.table( df1 , key = "b" )
dt2 <- data.table( df2 , key = "d" )

dt[ ldt , list( d ) , roll = "nearest" ]

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

然后玩这个技巧

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