为了账号安全,请及时绑定邮箱和手机立即绑定

如何使多个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 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);结果 html 应该是<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>我是一名初级开发人员,试图更好地编写 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 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>

`;


查看完整回答
反对 回复 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 info@iscafit.com.");

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

'''


查看完整回答
反对 回复 2023-11-12
  • 2 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信