簡體   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