【问题标题】:iFrame: using jQuery to add click event to buttoniFrame:使用jQuery向按钮添加点击事件
【发布时间】:2019-11-17 12:20:50
【问题描述】:

我正在做一个简短的测验,该测验将使用 HTML 和 JavaScript/jQuery 中的 iFrame 构建。我一直在试图弄清楚为什么我的按钮和 onclick 事件不起作用。

这是我在 HTML 中的内容:

<iframe id="iframe">

</iframe>

还有 JS:

$(document).ready(function() {

  function getDog() {
    alert("Dogs are great!");
  }

      var $iframe = $('#iframe');
      var $dogButton = "<button id=\'dog\'>Dog</button>";

      $iframe.contents().find("body").append("What is your favorite animal?");
      $iframe.contents().find("body").append($dogButton);
      document.getElementById("dog").addEventListener("click", getDog());
    })

由于某种原因,这在 sn-p 中不起作用,所以这是我的 CodePen:https://codepen.io/anfperez/pen/agRVKE

我知道这是用“旧”JS 编写的,但我使用的是旧版后端。

我以前没有真正使用过 iFrame。任何人都可以就为什么这不起作用提出一些建议吗?

【问题讨论】:

    标签: jquery html button iframe click


    【解决方案1】:

    您需要在 iframe 内容中找到狗按钮,就像您附加按钮一样。

    $iframe.contents().find(".dog").addEventListener("click", getDog());
    

    注意:如上所述,它不适用于 CORS(跨域)。仅当 iframe URL 位于同一域中时才有效

    【讨论】:

      【解决方案2】:

      试试这个$iframe.contents()[0].getElementById("dog").addEventListener("click", function() { getDog() });

      但这仅适用于托管在同一域中的 iframe。

      【讨论】:

        猜你喜欢
        • 2023-04-09
        • 2010-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-20
        相关资源
        最近更新 更多