亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

運行代碼以填充不同 html 頁面上的表單字段時出現未捕獲的 TypeError

運行代碼以填充不同 html 頁面上的表單字段時出現未捕獲的 TypeError

肥皂起泡泡 2023-10-04 14:34:41
我試圖使用這里的示例:https://developer.mozilla.org/en-US/docs/Web/API/Document/forms供我自己使用。上面的示例是訪問同一頁面上的表單。我的示例嘗試填充不同頁面上的字段。這是啟動器 html - launcher.html:<!DOCTYPE HTML><html><head><title>Launcher page</title><script>function launch(text) {    window.open("http://localhost/page2.html", '_blank');    let entryform = window.document.forms.newentry;    entryform.elements.town.placeholder = text;     window.focus();}</script></head><body><p>Click button to launch page2 and populate edit box on form</p><button type="button" id="launcher" onclick="launch('Edinburgh')">populate a text field on a different page</button></body></html>以及啟動的頁面 - page2.html:<!DOCTYPE html><html> <head>   <title>Page 2</title> </head> <body>  <header>     <h1>This page launched from launcher.html</h1>  </header>  <main>    <form name="newentry">      <p>Town: </p><input type="text" name="town" value="">    </form>  </main> </body></html>但是,當我單擊 launcher.html 上的按鈕時,launcher.html 頁面上出現錯誤:entryform.elements.town.placeholder = text;Uncaught TypeError: Cannot read property 'elements' of undefined  at launch (launcher.html:10)  at HTMLButtonElement.onclick (launcher.html:20)為什么這個元素屬性未定義?我怎樣才能解決這個問題?編輯我真正想做的很簡單,但是返回的 window.open 對象在我嘗試編輯時尚未準備好。真正簡單的解決方案是這樣的:function launch(text) {    let p2win = window.open('page2.html', '_blank');    p2win.onload = function(){        p2win.document.forms.newentry.town.value = text;    }}
查看完整描述

1 回答

?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

你的問題是這段代碼...


let entryform = window.document.forms.newentry;

正在當前窗口(即launcher.html)中查找表單元素。您可以做的是保存對彈出窗口的引用并通過該引用訪問其元素。


let popup = window.open("http://localhost/page2.html", '_blank')

let entryform = popoup.document.forms.newentry

// and so on

作為替代方案,我會考慮將查詢參數傳遞到彈出頁面,而不是嘗試在外部操作它。


例如


window.open(`page2.html?placeholder=${encodeURIComponent(text)}`, '_blank')

然后在page2.html...


<main>

  <form name="newentry">

    <p>Town: </p><input type="text" name="town" value="">

   </form>

</main>

<script>

let query = new URLSearchParams(location.search)

document.querySelector('form[name="newentry"] input[name="town"]')

  .placeholder = query.get('placeholder')

</script>

現場演示 ~ https://codesandbox.io/s/dependent-archimedes-51vn2


查看完整回答
反對 回復 2023-10-04
  • 1 回答
  • 0 關注
  • 100 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號