可以在父窗口中onSubmit Iframe
本文关键字:onSubmit Iframe 窗口 | 更新日期: 2023-09-27 18:29:11
是否可以在父窗口中调用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;
}
注意:我更新了代码笔片段