2013-05-29 56 views
0

我有兩個HTML頁面一個是parent.htm等是child.html在那裏我有在parent.htm' to child.html , here i have to access the elements of parent.htm in child.html`給出href,這裏有我的兩個文件如何使用java腳本訪問其他HTML表單中的一個HTML表單元素?

parent.htm

<!DOCTYPE html> 
<html> 


<body> 
<form> 
<input id=text1 type=text name="test2"> 
<a href="child.html" target="_self">Open kid</a> 
</form> 
</body> 
</html> 

child.html

<html> 
<script type="text/javascript"> 
function parent(){ 
    //here i want to access values from parent.htm page, but does not work 
var value = parent.getElementById('text1').value; 
    var value2=top.getElementById('text1').value; 
alert(value); 
} 
</script> 
<body onload="parent()"> 
<form> 
    </form> 
</body> 
</html> 

在此先感謝

+0

檢查這可能會幫助你http://stackoverflow.com/questions/13151634/callback-function-call-when-child-window-is-close – Hkachhia

+0

任何原因,你不能只是在客戶端上設置cookie和在第二頁閱讀它們? – Tim

+0

的要求是隻使用JS @Tim – MaheshVarma

回答

2

可能最簡單的方法來做你想做的是通過cookie。這是存儲在客戶端上的一個小文本文件,可以保持頁面中的值。如果您沒有指定過期日期,則當用戶關閉瀏覽器時,Cookie將過期。

Cookie tutorial

編輯

別的東西,你可以做的是使用JavaScript通過點擊鏈接,提交表單。我認爲它是formname.submit() - 這將允許您從表單文章中讀取值。 (雖然它會比閱讀cookie多一點點)

如果你只傳遞一個或兩個字段,我會使用cookie。除此之外,您可能需要考慮通過Javascript提交表單。

1

您應該可以讓用戶 window.opener獲取對父窗口的引用。

var parent = window.opener 

我看 - 你無法通過JavaScript訪問從以前頁面的DOM元素(據我所知)。

傳統上這是通過HTTP post變量處理的,通過一些後端過程將表單變量集合傳遞到後續頁面。

或者(如Moje指出)在新窗口中打開網頁,讓您可以訪問與window.opener

+0

但我沒有使用'window.open()'打開一個新窗口,它只是href鏈接@faust – MaheshVarma

1

第一個變化如下: -

<a href="child.html" target="_self">Open kid</a> 

到: -

<a href="child.html" target="_blank">Open kid</a> 

target =「_ self」表示子頁面將在s中打開ame父窗口,有效破壞父母及其代碼。

之後,訪問父的形式textbox元素有: -

var parentTextBox = window.opener.document.getElementById('text1'); 
+0

我的要求是在同一頁面打開child.html @Moje – MaheshVarma

+0

@ MaheshVarma是否考慮異步加載孩子的HTML UI並在隱藏父母的UI之後顯示它? – moje

+0

不,我沒有考慮過 – MaheshVarma

1

我認爲你不能做到這一點,至少你現在的樣子嘗試。

一旦你點擊「打開孩子」,你的當前頁面將被新的替換,所以你不能訪問該屬性。

你應該可以通過使用cookie來解決這個問題,在url中或Web Storage傳遞所需的值。

1

parent.htm

<!DOCTYPE html> 
<html> 
    <body> 
    <form method="GET" id="myform" action="child.html"> 
     <input id=text1 type=text name="test2"> 
     <a href="child.html" target="_self" onclick="document.getElementById('myform').submit();">Open kid</a> 
    </form> 
    </body> 
</html> 

child.html

<!DOCTYPE html> 
<html> 
<body onload="alert(window.location.toString().split('?')[1].split('=')[1])"> 

</body> 
</html> 

可能包含一些錯字,但這個想法是通過GET提交表單給孩子,然後讀得到window.location的參數在加載child.html之後。

+0

好主意,這是一個[小提琴](http://jsfiddle.net/GN5rW/6/),展示了類似的動作。 –

+0

謝謝@ShadowWizard - 我的示例代碼很髒,但我們不知道他將如何處理抓取的值。所以我只是做了這個醜陋的單線警報:) – ElmoVanKielmo

+0

是的,這是一般的想法,我的小提琴包含更通用的方法。 –