iT邦幫忙

0

[JS]跨頁面傳值

  • 分享至 

  • xImage

初學前端網頁,在練習時遇到疑惑,請各位開導,謝謝!

https://ithelp.ithome.com.tw/upload/images/20210701/20135967u2KRfLSzBv.png

情境:
在A.html上點下「開啟新視窗」按鈕,跳出B.html,在B.html內的文字框輸入文字後,點下「回傳」按鈕,B.html文字框內的值會送回到A.html的文字框內(且A.html不需要手動更新,於B.html點下「回傳」按鈕後A.html即顯示值)

目前撰寫的程式碼如下,我知道要在回傳按鈕的function內下指令,但是跨頁面傳送回A.html的部分需要求解...

【A.html】

<!DOCTYPE html>
<html>
<script>
	function btnOpen(){
        window.open ('B.html', 'B', config='height=560, width=700, top=200, left=700, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
	}
</script>
<body>

	<input type="text" name="txtReceive" id="txtReceive" />
	<br>
	<button onClick="btnOpen()" name="btnOpen" id="btnOpen" >開啟新視窗</button>

</body>
</html>

【B.html】

<!DOCTYPE html>
<html>
<script>
	function btnReturn(){
		var txtValue = document.getElementById('txtValue').value;
		
	}
</script>
<body>

	<button onClick="btnReturn()" name="btnReturn" id="btnReturn" >回傳</button>
	<br>
	<input type="text" name="txtValue" id="txtValue" />

</body>
</html>
archer9080 iT邦研究生 4 級 ‧ 2021-07-01 10:34:30 檢舉
open打開的話應該算是父子視窗傳值
href 跳轉的話應該能用url或是cookie
可以參考postMessage
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
1
海綿寶寶
iT邦大神 1 級 ‧ 2021-07-01 09:39:04
最佳解答

試試看

function btnReturn() {
    var txtValue = document.getElementById('txtValue').value;
    opener.document.getElementById('txtReceive').innerHTML = txtValue;
};

參考資料來源

希希寶 iT邦新手 4 級 ‧ 2021-07-01 10:49:01 檢舉

感謝大大!
套上去後發現有收到值,但是卻沒有顯示在文字框內,把innerHTML改成placeholder後就能顯示了~

archer9080 iT邦研究生 4 級 ‧ 2021-07-01 13:14:43 檢舉

應該是要用value
txtReceive是input text
innerHTML 用在div span等等
單純想顯示的話應該用div or span
後續還要更進一步傳值至後端或是修改的話才用text
placeholder算是提示之類的,點選text輸入就會被清空了

0
小魚
iT邦大師 1 級 ‧ 2021-07-01 09:30:57

使用GET或POST,
不過POST應該需要後端,
那就用GET吧.

希希寶 iT邦新手 4 級 ‧ 2021-07-01 10:51:00 檢舉

感謝~
不過用GET的話,網址列就會跟著帶值了吧?
不太希望網址列有變動><

0
nlstudio
iT邦新手 2 級 ‧ 2021-07-01 10:43:07

如果不藉其他語言(php,jsp,asp)傳遞
純 JS
請看這篇 透過取URL變數截取參數 location.search
https://blog.xuite.net/ahdaa/blog1/31825228

希希寶 iT邦新手 4 級 ‧ 2021-07-01 10:51:57 檢舉

謝謝!!!
不過不希望數值會出現在網址列上QQ
所以目前不會選擇使用GET方法~

我要發表回答

立即登入回答