繁体   English   中英

使用jquery或javascript生成HTML的模板

[英]templatization using jquery or javascript to generate html

我正在创建一个包含许多动态元素(添加了“ +”和“-”)的长HTML表单,并使用了jquery的.clone()方法,但我对此并不满意。 我想要的是单击“ +”,我将选择预定义的html并替换“ id / name”之类的某些部分,然后将其追加到现有部分。 这将使我的逻辑非常清晰。 例如,我在html下方单击“ +”,然后单击克隆并附加到现有视图(工作正常)

<div class='row'>
  <input id="ip_1" name="ip_1">
  <input date... id="dt_1" name="dt_1">
  <select ... id="sel_1">
  <br>
  <input with text ... id="ip_2">
</div>

我想要的是,我将在html变量上方保存html,然后仅传递new_id,new_name或其他参数以获取新的html,例如TT2,Jinja2或Angular,但我想保持它的轻便

function x(v, d, s, d2)  = {
  return '<div class='row'>
     <input id="{{ v }}" name="{{ v }}">
     <input date... id="{{ d }}" name="{{ d }}">
     <select ... id="{{ s }}">
     <br>
     <input with text ... id="{{ d2 }}">
  </div>'
}

有什么建议么?

您可以让Javascript为您完成所有工作。 下面的函数拾取块中的最后一行,然后相应地更新各个元素。 唯一的问题(我让您解决)是,如果您不能在现有块之间插入一个块。

function x(){
   // get all row elements
   var rows = document.getElementsByClassName('row');
   var last = rows.length - 1;

   //--- get current last element to duplicate
   var clone = rows[last].cloneNode(true);

   //--- get all the inputs with in the duplicate
   var inp = clone.getElementsByTagName('input');
   //-- update all the input elements
   inp[0].id = inp[0].name = IncrementValue(inp[0].id);
   inp[1].id = inp[1].name = IncrementValue(inp[1].id);
   inp[2].id = inp[2].name = IncrementValue(inp[2].id);;
   //--- get the select element
   inp = clone.getElementsByTagName('select');
   inp[0].name = IncrementValue(inp[0].id);
   //--- append all to the main div
   document.getElementsByTagName('body')[0].appendChild(clone);
}
function IncrementValue( str ) {
   var v = str.split('_');
   v[1]++;
   return v.join('_');
}

上面的脚本document.getElementsByTagName('body')[0]发生了变化。getElementsByTagName document.getElementsByTagName('body')[0]需要指向div容器作为输入。 html需要一个按钮: <button name='add' onclick="x()"> + </button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM