第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

元芳怎么了 2023-11-12 22:09:59
我正在 Contact7 電子郵件表單中通過 javascript 覆蓋一些 HTML 代碼。我有 3 個“p”標(biāo)簽,但我想不出一種方法可以使其更加干燥。這是我的代碼  //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 info@iscafit.com.";  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);結(jié)果 html 應(yīng)該是<div class=".wpcf7-response-output">  <p>Thank you for your order!</p>  <p>A confirmation email has been sent to you from info@iscafit.com.</p>  <p>Please keep the confirmation email for your records.</p></div>我是一名初級開發(fā)人員,試圖更好地編寫 DRY 代碼。任何建議,將不勝感激!
查看完整描述

2 回答

?
慕的地10843

TA貢獻(xiàn)1785條經(jīng)驗 獲得超8個贊

創(chuàng)建一個函數(shù),您可以使用要附加的文本進(jìn)行調(diào)用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 info@iscafit.com.');

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 info@iscafit.com.</p>

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

`;


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

TA貢獻(xiàn)1825條經(jīng)驗 獲得超6個贊

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


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


'''


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 info@iscafit.com.");

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

'''


查看完整回答
反對 回復(fù) 2023-11-12
  • 2 回答
  • 0 關(guān)注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號