gpt4 book ai didi

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

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

是否可以在父窗口中调用 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/

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