【问题标题】:Trigger a button click inside an iframe [duplicate]在 iframe 内触发按钮单击 [重复]
【发布时间】:2015-02-04 14:15:37
【问题描述】:

这是 iframe 代码:

<div id="OutDiv" class="outerdiv">
    <iframe src="http://beta.sportsdirect.bg/checkout/onepage/" id="InnerIframe" class="FrameCSS" scrolling="no"></iframe>
</div>

这是上面 iframe 调用的按钮的 HTMl 代码:

<button type="button"  id="SuperWebF1" title="Continue" class="button">Continue</button>

这是我用来在页面加载时触发按钮单击的 jQuery 函数:

 $('#SuperWebF1').trigger( "click" );

但只有当我将 jQuery 代码放在按钮的源代码中并且 iframe 使用脚本调用按钮时,它才会这样工作。

我想制作一个从 iframe 外部单击按钮的事件。 有可能吗?

提前致谢!

【问题讨论】:

标签: javascript jquery html iframe


【解决方案1】:

注意:如果 iframe 的 src 指向跨域页面,.contents() 不起作用。更多:Cross domain iframe issue 和 Get DOM content of cross-domain iframe

//execute code after DOM is ready
$(function() {

  //find iframe
  let iframe = $('#main_iframe');
  
  //find button inside iframe
  let button = iframe.contents().find('#main_button');
  
  //trigger button click
  button.trigger("click");
  
});
<!--Add jQuery library-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

如果您需要在 iframe 中操作其他页面,请搜索官方 API 或 GET 参数。 示例:Youtube Embed Video、Google Maps Embed Api

【讨论】:

  • 代码只回答没有解释为什么应该考虑该代码通常在这里是不可接受的。您能否编辑以添加解释,说明您认为这回答了问题的原因?
  • 非常适合我
  • 能否提供浏览器支持或某种官方来源?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多