Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取iframe内已单击标记的父级_Javascript_Jquery_Html_Iframe - Fatal编程技术网

Javascript 获取iframe内已单击标记的父级

Javascript 获取iframe内已单击标记的父级,javascript,jquery,html,iframe,Javascript,Jquery,Html,Iframe,我有一个包含HTML页面的iframe。现在我想获取单击的父项的类。 这是我的简历: <iframe src="//example.com" id="frame" ></iframe> 这是我的剧本: $(document).ready(function() { var iframe = document.getElementById('frame'); var innerDoc = iframe.contentDocument || iframe.cont

我有一个包含HTML页面的iframe。现在我想获取单击的父项的类。
这是我的简历:

<iframe src="//example.com" id="frame" ></iframe>  
这是我的剧本:

$(document).ready(function() {
  var iframe = document.getElementById('frame');
  var innerDoc = iframe.contentDocument || iframe.contentWindow.document.body;
  $(innerDoc).on('click', function(e) {
    var thisID = ((e.target).id);
    alert(thisID);
    alert(innerDoc.getElementById(thisID));


    $(thisID).click(function() {
      var Allclassnames = $(thisID).parent();
      console.log(Allclassnames);
    });
  });
});
但它返回的项目仅被单击。如何修复它

演示:

注意
:它们在同一个域中。可能下面的
演示
由于这个原因不起作用。但我确信我的HTML与我的网站在同一个域中。
谢谢。

除非与父文档位于同一域中,否则无法与
iframe
的内容交互

请参阅:

将沙盒属性添加到iframe

<iframe src="/example.html" id="frame" sandbox="allow-scripts allow-same-origin"></iframe> 

将脚本更改为

<script>
$('#frame').load(function() {
  $('#frame').contents().on('click', function(e) {  
    var thisID = ((e.target).id);
    alert(thisID); 
    alert($('#'+thisID,this));
      $('#'+thisID,this).click(function() {
        var Allclassnames = $(this).parent();
        console.log(Allclassnames); 
      });
  });
});
</script>

$('#frame')。加载(函数(){
$('#frame').contents()。在('click',函数(e){
var thisID=((e.target.id);
警报(thisID);
警报($('#'+thisID,this));
$('#'+thisID,this)。单击(函数(){
var Allclassnames=$(this.parent();
log(所有类名);
});
});
});
确保框架文档中的每个元素。具有某些id,否则alert()可能会引发错误

要查看iframe的控制台消息,您需要从scope下拉列表中更改scope,它位于控制台选项卡中,chrome开发者工具中的过滤器图标除外

<script>
$('#frame').load(function() {
  $('#frame').contents().on('click', function(e) {  
    var thisID = ((e.target).id);
    alert(thisID); 
    alert($('#'+thisID,this));
      $('#'+thisID,this).click(function() {
        var Allclassnames = $(this).parent();
        console.log(Allclassnames); 
      });
  });
});
</script>