首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JSP/JS 根據按鈕動態填入不同輸入框:通用 click handler 實作

     編輯:程式設計綜合問答

需求

三個輸入框:收件人 i_rescive、抄送 i_cc、密送 i_bcc。點擊對應「添加」按鈕,彈窗選取聯絡人後,將 Email 填入對應輸入框。

核心思路:按鈕 ID 對應輸入框 ID

按鈕 id="btn_rescive" → 輸入框 id="i_rescive",以 btn_ / i_ 前綴對應。

完整可執行範例 (純前端示範)

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>聯絡人填入示範</title><style>
  textarea { width:300px; height:60px; display:block; margin:4px 0; }
  button { margin:2px; }
</style></head><body>
<h3>主視窗</h3>
<textarea id="i_rescive" placeholder="收件人"></textarea>
<button id="btn_rescive" onclick="openPicker(this)">添加收件人</button>
<br>
<textarea id="i_cc" placeholder="抄送"></textarea>
<button id="btn_cc" onclick="openPicker(this)">添加抄送</button>
<br>
<textarea id="i_bcc" placeholder="密送"></textarea>
<button id="btn_bcc" onclick="openPicker(this)">添加密送</button>

<script>
function openPicker(btn) {
  // 實際專案:window.open('selectUser.jsp', 'picker', 'width=400,height=500');
  // 這裡模擬 picker 回傳
  const emails = prompt('輸入 Email,分號分隔:', 'a@x.com;b@y.com');
  if (!emails) return;
  // 依按鈕 ID 推導目標輸入框 ID
  const targetId = 'i_' + btn.id.slice(4); // 去掉 "btn_"
  document.getElementById(targetId).value += emails + ';';
}
</script>
</body></html>

彈窗頁面 回傳邏輯

<!-- picker.jsp / selectUser.jsp -->
<script>
function confirmSelection() {
  const selected = [...document.querySelectorAll('[name=cbUserName]:checked')]
                     .map(cb => cb.value + '@domain.com')
                     .join(';');
  if (!selected) { alert('請選擇聯絡人'); return; }
  // 寫入 opener 視窗對應輸入框
  // 假設 opener 已開啟時帶入 targetId 參數,或由 opener 傳遞 callback
  // 簡單做法:opener 視窗定義全域函數 receiveEmails(targetId, emails)
  if (window.opener && window.opener.receiveEmails) {
    window.opener.receiveEmails(window.opener._currentTargetId, selected);
  }
  window.close();
}
</script>

主視窗配合寫法

// 主視窗
let _currentTargetId = null;
function openPicker(btn) {
  _currentTargetId = 'i_' + btn.id.slice(4);
  window.open('picker.jsp', 'picker', 'width=400,height=500');
}
function receiveEmails(targetId, emails) {
  document.getElementById(targetId).value += emails + ';';
}

進階:使用 postMessage (跨域安全)

// 主視窗
window.addEventListener('message', e => {
  if (e.origin !== 'https://your-domain.com') return;
  if (e.data.type === 'emails') {
    document.getElementById(e.data.targetId).value += e.data.emails + ';';
  }
});
// 彈窗
window.opener.postMessage({type:'emails', targetId:_currentTargetId, emails:selected}, 'https://your-domain.com');

關鍵點總結

  1. ID 命名規約:btn_* ↔ i_*,單一 handler 通用。
  2. 彈窗通訊:同域用 window.opener 直接呼叫;跨域用 postMessage。
  3. 避免全域變數衝突:用 IIFE/模組封裝 _currentTargetId。
  4. JSP 中輸出 JS 變數:<%=basePath%> 等需確保正確編碼,防 XSS。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved