javascript - 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!
解决方案
这里应该有足够的工具来做你想做的事
除非您稍后设置 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>
更多的:
推荐阅读
- hibernate - 如何在不使用 JPA 的情况下保持在 SpringBoot/GraphQL 中打开的 Hibernate 事务?
- c++ - 在 C++ 中快速添加二维数组
- lisp - LISP:修改列表时(使用 `nth`),所有元素都会更改
- javascript - 问题在 keyup 搜索输入(分页)上显示正确的项目数
- typescript - 如何键入将在 TypeScript 中使用命名导入导入的未知导出?
- javascript - window.getAttention() 发生了什么,我可以改用什么?
- ios - 如何使用 Swift 在 iOS 中将音频格式从 mp3 转换为 wav?
- c# - 如何运行两个while循环?
- reactjs - 如何在 React/JSX 中触发 onSelectStart?
- android - 如何使用 android studio 中的按钮更改图像?