2016-05-04 27 views
1

我有一个包含HTML页面的iframe。现在我想要获得单击的父项目的类。
这是我ifram:获取iframe中点击标签的父母

<iframe src="//example.com" id="frame" ></iframe> 

是css:

#frame{ width:380px; height:420px;} 

这是我的脚本:

$(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); 
    }); 
    }); 
}); 

,但回报的项目被点击only.how修复它?

演示:DEMO

NOTE:这些都是在下面DEMO同一domain.maybe不工作了这reason.but我敢肯定,我的HTML是我的网站同一个域的内部。 谢谢。

回答

1

添加沙箱属性的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> 

确保在框架文档的每一个元素。有一些ID或者alert()可能会引发错误。

要查看iframe的控制台消息,您需要从作用域下拉列表中更改作用域,它位于除chrome开发人员工具中的筛选器图标之外的控制台选项卡中。