首页 > 解决方案 > 如何从 Iframe 内部调用 html 点击事件的服务器端函数?

问题描述

标签: javascriptc#htmlasp.net

解决方案


您不能直接调用服务器端函数。但是使用一些简单的 jQuery 是可能的。

在包含 iframe 的页面上放置以下代码

<iframe src="index.html" width="200" height="100" frameborder="1"></iframe>

<asp:Label ID="Label1" runat="server"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" ClientIDMode="Static" OnClick="Button1_Click" />

<script type="text/javascript">
    function executeIframeCode() {
        $('#Button1').click();
    }
</script>

然后在 iframe 中放置一个按钮或任何您想要的并executeIframeCode在父级中调用该函数。

<button onclick="parent.executeIframeCode()" type="button">
    Execute Parent Code
</button>

代码背后的父代码

protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = "Called from Iframe!";
}

这仅适用于 iframe 页面位于同一域中的情况。


推荐阅读