问题描述
我正在尝试将事件侦听器附加到 IFrame 中页面上按钮的单击"事件.iframe 中的页面与父窗口属于同一域.
I'm trying to attach an eventlistener to the "click" event of a button on a page in an IFrame. The page in the iframe belongs to the same domain as the parent window.
window.frames["iframe_Id"].document.getElementById("button_id").addEventListener("click",functionToRun,false);
以上示例对我不起作用.这可能只是我实际代码中的语法错误,但我想看看这是否是总体思路.
The above sample is not working for me. It could just be a a syntax error in my actual code but I wanted to see if this is the general idea.
注意:我找到了很多关于将点击事件添加到整个 Iframe 的示例,但我不确定它对 Iframe 中的按钮是否同样有效.
Note: I found plenty of examples on adding the click event to the entire Iframe but I'm not sure it works the same for buttons within the Iframe.
推荐答案
使用 jQuery:
$("#iframe_Id").contents("#button_id").click(functionToRun);
或者不使用 jQuery:
Or without jQuery:
document.getElementById("iframe_Id").contentWindow.document.getElementById("button_id").addEventListener("click", functionToRun, false);
这仅在 iframe 符合 同源政策时有效.
This will only work if the iframe meets the same origin policy.
这篇关于IFrame 按钮点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!