2013-04-20 48 views
0

我可以使用哈希鏈接在iframe中運行jquery函數嗎? 或許是這樣的:使用哈希鏈接在iframe中運行jquery函數

父代碼:

<a href="#runFunction" target="iframe">run function in iframe</a> 
<iframe src="pageName.html" name="iframe"></iframe> 

的iframe代碼:

$(document).ready(function(){ 
$('body').the parent link is clicked, changing the url to pageName.html#runFunction (function(){ 
//blah blah blah// 
}); 
}); 

感謝

回答

1

是的,你可以使用hashchange事件。只要你不介意不支持IE7 http://caniuse.com/hashchange

另外,還有,會爲你回填插件:http://benalman.com/projects/jquery-hashchange-plugin/

在父頁面簡單的iframe的網址更改爲新的哈希值。

$("iframe").prop("src", "http://google.com/#newhash"); 

然後在iframe頁面docready:

$(window).bind("hashchange", function() { 
    alert(window.location.hash); 
}); 
0

我不知道你想在這裏到底是什麼...但你可以試試這個:

其中 'myIFrameFunction'是 'pageName.html' 的內部功能...

父HTML:

<a href="#myIFrameFunction" target="iframe">click me for win</a> 
<iframe src="pageName.html"></iframe> 

的iFrame的JavaScript(只要被調用的函數被聲明爲全局[在腳本標籤或js文件直接]):

function testHash() { 
    var hash = window.location.hash.split('#')[1]; 
    if (typeof window[hash] != 'undefined') { 
     window[hash](); 
    } 
} 

var myTimer = setInterval(testHash, 100); 

function myIFrameFunction() { 
    alert('It Works!'); 
}