jQuery 触发对 iFrame 的点击?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16928860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:05:23  来源:igfitidea点击:

jQuery to trigger a click on an iFrame?

jquery

提问by user2453693

If a user clicks on an image I want that to simultaneously trigger a click on a specified iFrame as well. Is that possible? The image and iFrame are located on the same page. If so, can you please show me the code that would work?

如果用户单击图像,我希望它同时触发对指定 iFrame 的单击。那可能吗?图像和 iFrame 位于同一页面上。如果是这样,你能告诉我有效的代码吗?

Here's what I have so far:

这是我到目前为止所拥有的:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<img id="image" src="https://www.google.com/images/srpr/logo4w.png">

<iframe id="iframe" src="http://www.test.com" height= "100" width="160"></iframe>

<script>
jQuery("input.image").click(function(){
   $("#iframe").click()
});
</script> 

</body>
</html>

回答by dcarson

Your jquery image selector is wrong.

您的 jquery 图像选择器是错误的。

change

改变

jQuery("input.image")

to

$("#image")

Then everything will work. You can see it in this fiddle

然后一切都会好起来的。你可以在这个小提琴中看到它

Post Edit

帖子编辑

If the question is to trigger a click on one of the elements contained in the iFrame, then replace the

如果问题是触发对 iFrame 中包含的元素之一的点击,则替换

$("#iframe").click()

with something like:

像这样:

$("#iframe").contents().find("a:first").click();

This will only work if the contents of the main page and the iFrame's page are on the same domain. Otherwise browsers will prevent the action as it is cross site scripting. You can see in your example, XSS prevention will occur as demonstrated in this fiddle

这仅在主页的内容和 iFrame 的页面位于同一域中时才有效。否则浏览器将阻止该操作,因为它是跨站点脚本。您可以在您的示例中看到,XSS 预防将如此小提琴所示

回答by pvnarula

I think you needed something like this:-

我想你需要这样的东西:-

$("#image").click(function(){
     var $iframe = $("#iframe").contents();
     $("body", $iframe).trigger("click");
});