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

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

如何使多個innerHTML javascript 語句更加DRY

如何使多個innerHTML javascript 語句更加DRY

元芳怎么了 2023-11-12 22:09:59
我正在 Contact7 電子郵件表單中通過 javascript 覆蓋一些 HTML 代碼。我有 3 個“p”標簽,但我想不出一種方法可以使其更加干燥。這是我的代碼  //remove default HTML//  document.querySelector('.wpcf7-response-output').innerHTML = '';    //Add first p tag and text//  var p1 = document.createElement('p');  p1.innterHTML ="Thank you for your order!";  document.querySelector('.wpcf7-response-output').appendChild(p1);    //Add second p tag and text//  var p2 = document.createElement('p');  p2.innerHTML = "A confirmation email has been sent to you from [email protected].";  document.querySelector('.wpcf7-response-output').appendChild(p2);    //Add third p tag and text//  var p3 = document.createElement('p');  p3.innerHTML = "Please keep the confirmation email for your records."  document.querySelector('.wpcf7-response-output').appendChild(p3);結果 html 應該是<div class=".wpcf7-response-output">  <p>Thank you for your order!</p>  <p>A confirmation email has been sent to you from [email protected].</p>  <p>Please keep the confirmation email for your records.</p></div>我是一名初級開發人員,試圖更好地編寫 DRY 代碼。任何建議,將不勝感激!
查看完整描述

2 回答

?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

創建一個函數,您可以使用要附加的文本進行調用p:


const container = document.querySelector('.wpcf7-response-output');

container.innerHTML = '';

const append = (text) => {

  container.appendChild(document.createElement('p')).textContent = text;

};

append('Thank you for your order!');

append('A confirmation email has been sent to you from [email protected].');

append('Please keep the confirmation email for your records.');

或者只是分配新的 HTML 字符串:


document.querySelector('.wpcf7-response-output').innerHTML = `

  <p>Thank you for your order!</p>

  <p>A confirmation email has been sent to you from [email protected].</p>

  <p>Please keep the confirmation email for your records.</p>

`;


查看完整回答
反對 回復 2023-11-12
?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

干得好。您可以通過這種方式消除重復,同時保持函數的通用性。


泛化能力極大地有助于減少代碼。下面的appendChild函數不僅可以用于此父子組合,還可以用于任何其他父子組合。


'''


function appendChild(parentSelector,childTagname,innerhtml)

  {  

      var childel = document.createElement(childTagname);

      childel.innterHTML =innerhtml;

      document.querySelector(parentSelector).appendChild(childel);  

  }

  

  appendChild('.wpcf7-response-output','p',"Thank you for your order!");

  appendChild('.wpcf7-response-output','p',"A confirmation email has been sent to you from [email protected].");

  appendChild('.wpcf7-response-output','p',"Please keep the confirmation email for your records");

'''


查看完整回答
反對 回復 2023-11-12
  • 2 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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