2017-03-08 64 views
0

我一直在尋找解決方案,但我找到的所有解決方案都沒有奏效。我想要獲取文檔中的iframe中發生的點擊。我收到了「準備好文檔」的提醒,但是無論我點擊哪個位置,我都不會收到「iframe點擊」提醒。我使用ASP.NET MVC 5.下面的代碼:iframe的功能onclick方法

@Scripts.Render("~/bundles/jquery") 
@{ 
    ViewBag.Title = "Home Page"; 
} 

<div id="terminal-iframe-wrap" class="map-info-wrapper" style="display: none"> 
    <iframe name="terminal-iframe" id="terminal-iframe" class="terminal-url-wrapper" frameBorder="0"></iframe> 
</div> 

<div id="all-terminals-view" class="map-info-wrapper"> 
    <div id="map" class="map"></div> 

</div> 

@section scripts 
{ 
    <script src="~/Scripts/lib/promise.min.js"></script> 
    <script src="~/Scripts/lib/fetch.js"></script> 
    <script src="~/Scripts/app/map.js"></script> 
    <script async defer src="//maps.googleapis.com/maps/api/js?key=somethingsomething&callback=initMap"></script> 
    <script> 
     $(document).ready(function() { 
      alert("document ready."); 
      document.getElementById('terminal-iframe').contentWindow.document.body.onclick = function (event) { 
       alert("iframe clicked"); 
       if (e.target.id != "right-side-menu" && !$(e.target).parents("#right-side-menu").size()) { 
        if ($('#right-side-menu').hasClass('in')) { 
         $('#right-side-menu').collapse('hide'); 
        } 
       } 
      }; 
     }); 
    </script> 
} 

回答

0

你可以用它喜歡:

jQuery有一個方法,稱爲.contents(),該IFRAME元素上使用時返回iframe的文檔。

// Get a reference to the iframe document 
var iframeDoc = $('#iFrame').contents().get(0); 

// Bind event to iframe document 
$(iframeDoc).bind('click', function(event) { 
    // do something 
}); 

這將適用於你。

欲瞭解更多詳情,請訪問:http://api.jquery.com/contents/

+0

仍然不起作用。當我點擊iframe時沒有任何反應。 –

0

JavaScript代碼看作是OK,請參見下面的codepen:

http://codepen.io/anon/pen/ryWoKX?editors=1010

$(document).ready(function() { 

    document 
    .getElementById('terminal-iframe') 
    .contentWindow.document.body.onclick = function (event) { 
       console.log('clicked !'); 
    }; 
}); 

您的問題是,你有一個「顯示器:none「in#terminal-iframe-wrap

+0

如果顯示屏沒有顯示,我能看到它嗎? iframe肯定是可見的,但您在這裏和在codepen中編寫的代碼仍然不適用於我。 –

+0

我在另一個文件中用'onclick'函數將'display'屬性改爲'inline'。 –