2014-04-17 75 views
-1

例如同一個JavaScript函數page1.html我:訪問不同的HTML頁面

<input type="radio" id="id1" onclick="change()">Radio Button</input> 

page2.html我:

<a href="page3.html" id="id2">Link</a> 

點擊單選按鈕page1.html應更改page2.html中href屬性的值。

的Javascript(js_file.js):

function change() 
{ 
    if(document.getElementById(id1).checked) 
     { 
      document.getElementById(id2).href="page4.html"; 
     } 
} 

此代碼不會因爲工作ID1和ID2不要在同一頁面上。

是否有任何方法,其中2個或更多的HTML頁面可以同時訪問一個JavaScript函數?

假設我已經包含了這一點:

<script src="js_file.js" type="text/javascript" /> 
在兩個 標籤內的HTML頁面

我試圖避免服務器端編程,因爲它是一個嵌入式Web服務器,只能用C語言編程。

+0

。利用查詢字符串的簡單方法。 – Hatsjoem

+0

當行動發生在第1頁,使用本地存儲。當你加載第2頁,檢查localStorage的它存儲結果,如果它存在,從LocalStorage加載數據 – enhzflep

+3

這個問題表明對Web的工作原理缺乏瞭解,如果你想要做這樣的事情,你需要一個服務器端語言而不是JS,或者是js + websockets,如果你正在做實時的話。 –

回答

0

嘗試此尺寸。

Page1.html

<!DOCTYPE html> 
<html> 
<head> 
<script> 
window.addEventListener('load', onDocLoaded, false); 

function onDocLoaded() 
{ 
    var urlRadios = document.getElementsByName('urlSelector'); 
    var i, n = urlRadios.length; 
    for (i=0; i<n; i++) 
     urlRadios[i].addEventListener('click', onUrlRadioChange, false); 
} 

function onUrlRadioChange(evt) 
{ 

    localStorage.destUrl = this.getAttribute('dest'); 
    localStorage.destTxt = this.getAttribute('msg'); 
} 

</script> 
<style> 
</style> 
</head> 
<body> 
    <h3>Pick destination of link on page 2</h3> 
    <input type='radio' msg='No page selected' dest='none' checked name='urlSelector'>none</input> 
    <input type='radio' msg='Page 3' dest='page3.html' name='urlSelector'>page3.html</input> 
    <input type='radio' msg='Page 4' dest='page4.html' name='urlSelector'>page4.html</input> 
    <hr> 
    <a href='page2.html'>Page 2</a> 
</body> 
</html> 

Page2.html

<!DOCTYPE html> 
<html> 
<head> 
<script> 
function byId(e){return document.getElementById(e);} 
window.addEventListener('load', onDocLoaded, false); 

function onDocLoaded() 
{ 
    if (localStorage.destUrl != 'none') 
     byId('tgtLink').href = localStorage.destUrl; 
    byId('tgtLink').innerHTML = localStorage.destTxt; 
} 
</script> 
<style> 
</style> 
</head> 
<body> 
    <h3>Destination was set by page 1</h3> 
    <a id='tgtLink'>Link</a> 
</body> 
</html> 
+0

非常感謝:) – user3544005

0

要做到這一點,唯一的方法是使用hiddenHTML元素在頁面之間傳遞數據。

第1頁

<input type="radio" name="radio1" id="radio1" onclick="change.js">Radio Button</input> 

第2頁

<input type="hidden" name="radio1" value="XXX"> 

當然,你必須有Page1上傳表單服務器,讓服務器與hidden產生Page2元素填充。

+0

不需要沒有stinkin'的服務器,也沒有一個隱藏的表單元素之三。 :p您可以使用在本地機器上運行的JavaScript和文件輕鬆完成此操作 - 甚至不需要通過本地主機訪問它們。 – enhzflep

+0

@enhzflep啓發我們嗎? –

+0

@enhzflep是的,是的,事情可能被塞進怪異的角落和縫隙 - 你可以在window.name中隱藏東西 - 但是如果沒有服務器來處理表單,那麼採集數據的用途是什麼。 –

0

另一種解決方案可能工作,如果網站的結構允許這樣的:window.opener
假設頁面1將第2頁打開爲彈出窗口(因此兩個窗口都保持打開狀態),那麼您可以訪問第1頁到window.opener中的所有內容。
你甚至可以在這裏測試。在新窗口中打開該站點上的任何鏈接(在stackoverflow的域中,否則將是XSS),然後打開該窗口的JavaScript控制檯並輸入:window.opener.document.title =「YAY!「
至少,這是爲了避免使用本地存儲等