javascript - 父窗口中的 Iframe 的 onSubmit 可以吗?

标签 javascript c# jquery html iframe

是否可以在父窗口中调用 iframe 的 onsubmit 函数?我需要这个,因为我想检查 iframe 何时提交并将 iframe 文本框的某些值传递到父窗口中的文本框。

这是父窗口中的 jQuery,ExpDate 是 iframe 中的文本框。

var expDate = $("#ExpirationDate").text();
$('#frmAdd').on('submit', function (e) {
    e.preventDefault();
    if (expDate != null && expDate != "") {;
        $('#ExpDate', window.parent.document).val(expDate);
    }
});

最佳答案

我在 codepen 上做了一个演示,因为 SO 片段是沙盒的:

http://codepen.io/VincentCharpentier/pen/KVWyeK

重要部分:

// From the parent frame :
// 1. get the iframe with id "myFrame"
// 2. get the element with id "myForm" in this iframe (your form)
// 3. add an event handler
window.frames["myFrame"].contentWindow.document
      .getElementById("myForm")
      .onsubmit = function() { 
          alert("Submit !");
          // return false if you want to avoid redirection
          // return false;
      }

一旦获得了 iframe 的 document 对象,您就可以自由地对主 document 对象执行任何操作。

因此,如果需要,您可以将 .getElementById("myForm") 替换为 .getElementsByTagName("form")[0]

<小时/>

编辑

当您询问如何访问 iframe 中的其他元素时,它是:

在顶部框架中,您可以保留 iframe 的窗口元素的引用:

// keep a reference to the window element of the iframe :
var winIFrame = window.frames["myFrame"].contentWindow;

这样你就可以访问 iframe 中的任何 DOM 元素:

winIframe.document.getElementByID("SomeID")
winIframe.document.getElementsByTAgName("SomeTagName")
// ...

因此对于文本区域,您有两个选择:

1 - 如果文本区域位于表单内:

// add the event onsubmit handler
winIFrame.document.getElementById("myForm").onsubmit = function() { 
    // "this" refers to the form element
    // querySelector takes CSS selector as argument (like jQuery)
    // return the first element that match
    alert(this.querySelector("#ExpirationDate").value);
    return false;
}

2 - 如果您需要与表单之外的内容进行交互,请使用 winIFrame.document :

// add the event onsubmit handler
winIFrame.document.getElementById("myForm").onsubmit = function() { 
    // "this" refers to the form element
    // querySelector takes CSS selector as argument (like jQuery)
    // return the first element that match
    alert(winIframe.document.getElementById("ExpirationDate").value);
    return false;
}

注意:我更新了 codepen 代码段

关于javascript - 父窗口中的 Iframe 的 onSubmit 可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34629516/

相关文章:

c# - 如何覆盖 WPF 上的 onclose 事件?

javascript - JQuery 从 <li> 获取值

javascript - 在鼠标悬停/悬停期间仅从特定文本段落中获取数字

javascript - 跨域弹出窗口

c# - 从 ASP.NET 异步执行 SSIS 或 DTS 包

c# - 使用 Assert 语句时有什么方法可以忽略 Possible Null Reference Exception 警告?

javascript - 用于移动应用程序的 JQuery slider

javascript - 为什么 Nexus 4(使用 Android 版 Chrome)显示窗口大小为 384x519,但屏幕截图显示 768x1038?

Javascript 到 Python 数学转换

javascript - 创建和销毁 shieldUI 小部件