2014-10-31 191 views
1

現在我正在處理一個簡單的HTML/jQuery腳本,在這裏我想要更改iframe高度,當我單擊加載的按鈕時它自己的iframe。jQuery - 在iframe中的按鈕的onclick事件中更改Iframe高度

看看我的代碼:

的index.php:

<div id="outerdiv"> 
    <iframe src="http://beta.sportsdirect.bg/test/iframe.php" id="inneriframe" scrolling="no" target="_parent"></iframe> 
</div> 

iframe.php:

<HTML> 
<head> 
<script src="//code.jquery.com/jquery-1.10.2.js"></script> 
</head> 
    <script type="text/javascript"> 
    $("#SuperWebF1").click(function(){ 

     $('#inneriframe, #outerdiv', window.parent.document).css({"height":"450px"}); 

    }) 
    </script> 
<div style="display:block;height:300px;"> 
    <h3>The iframe content</h3> 
     <button type="button" id="SuperWebF1">Click me to resize the holding Iframe!</button> 
    </div>   

這裏是index.php文件的演示:http://beta.sportsdirect.bg/test/

當你打開它時,你會看到由iframe加載的按鈕。 當您點擊按鈕時,iframe不會改變高度!

爲什麼,有沒有錯誤?

你能幫我做這件事嗎?

提前致謝!

+0

您正嘗試將click事件綁定到button元素,然後它存在。 – CBroe 2014-10-31 20:06:50

+0

有沒有什麼辦法可以將腳本放在iframe之外,並讓它在該按鈕上的iframe內單擊有點擊? – user2942786 2014-10-31 21:31:52

回答

0

您需要先獲取iframe的內容,然後才能設置您的點擊事件。試試這個吧 -

var iframeDoc = $('#inneriframe').contents().get(0); 
$(iframeDoc).on('click', 'SuperWebF1', function() { 
     ........... your code here ............. 
}); 

快樂編碼!!!

2

以下是我對代碼所做的一些更改。

//function call needed to make sure page is loaded before javascript runs 
$(document).ready(function(){//begin document ready function 

//on click event 
$(document).on("click","#SuperWebF1",function(){//begin on click event 

    //change the height of selected elements 
    $('#inneriframe, #outerdiv', window.parent.document).css({"height":"450px"}); 

    });//end on click event 


    });//end document ready function 
+0

有沒有什麼辦法可以將腳本放在iframe之外,並讓它在該按鈕上的iframe中點擊 – user2942786 2014-10-31 21:36:50