首页 > 解决方案 > Get the class of an element clicked upon in an iframe?

问题描述

How can I get the class of an element clicked upon in an iframe?

HTML:

<input id="tag" type="text">

<iframe id="framer" src="SameDomainSamePort.html"></iframe>

JS:

$(document).ready(function () {
    $("iframe").each(function () {
        //Using closures to capture each one
        var iframe = $(this);
        iframe.on("load", function () { //Make sure it is fully loaded
            iframe.contents().click(function (event) {
                iframe.trigger("click");
            });
        });

        iframe.bind("click", function(e) {
            // always returns the iframe rather than the element selected within the iframe...
            $("#tag", window.top.document).val($(e)[0].target.className);
            return false;
        });
    });
});

Would it be easier to inject js?

And could I add css as well?

All help is appreciated!

标签: javascriptjqueryhtml

解决方案


这里应该有足够的工具来做你想做的事

除非您稍后设置 src,否则无法使用 load 事件,因为它在您运行代码时已经触发

小提琴作品:https ://jsfiddle.net/mplungjan/kqeqzusf/

所以有更严格的沙盒问题,但也要看看 SecurityError: Blocked a frame with origin from access a cross-origin frame

$(function() {
  $(".iframe").each(function(i) {
    var doc = $(this)[0].contentWindow.document;
    var $body = $('body',doc);
    $body.html(`<div id="test${i}">Click me ${i}</div>`); // or set the source
    $body.on("click",function(e) { // assign a handler
      console.log(e.target.id);
    });
  });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="container">
  <iframe id="iframe1" class="iframe"></iframe>
  <iframe id="iframe2" class="iframe"></iframe>
</div>

更多的:


推荐阅读