2016-05-04 26 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開發人員工具中的篩選器圖標之外的控制檯選項卡中。