2013-02-22 56 views
2

的index.html此代碼如何用JS或jQuery的

<iframe src="other.html" width="100%" height="600px"></iframe> 

<input type="button" id="btnOutside" value="Click me"/> 

的一個iframe的內容在other.html交互我有這樣的代碼:

<input type="button" id="btnInside" value="Other Click"/> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $("#btnInside").click(function() { 
     alert('inside'); 
    }); 
}); 
</script> 

我想使外部按鈕觸發這樣的內部按鈕index.html

<script type="text/javascript"> 
$(document).ready(function() { 
    $("#btnOutside").click(function() { 
     $("#btnInside").click(); 
    }); 
}); 
</script> 

但是是行不通的。我能做什麼??

回答

8

不同的iframe具有不同的上下文和文檔:當您調用$('#btnInside')時,jQuery正在主機iframe中執行並查看該文檔,因此無法找到它。如果嵌套的iframe位於同一臺服務器上,則可以從主機文檔中鏈接到其文檔:

$(document).ready(function() { 
    $("#btnOutside").click(function() { 
     $('iframe[src="other.html"]').contents().find("#btnInside").click(); 
    }); 
}); 
+0

感謝隊友的工作原理。 – kilkadg 2013-02-22 17:34:33