使用模板文字作为对象

时间:2019-05-11 18:59:59

标签: javascript

我在表的末尾有一个输入,我希望它的每一行都有不同的ID。我做了这样的事情:

`<td><input type="number" name="quantity${article.ID}" id="quantity${article.ID}" min="1" max="5"></td>`

这很好用,因为当我查看html时,它给了我类似:quantity1,quantity2等。

问题是,当我尝试动态调用这些ID时,它将返回null。这是完整的javascript代码:

//load JSON file
var articles = ""
var txt = ""
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
  if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
    articles = xmlhttp.responseText;
    txt = JSON.parse(articles);
    console.log(txt);

    processArticles(txt);

    processForm(txt);

  }
};
xmlhttp.open("GET","../articles.json",true);
xmlhttp.send();

function processArticles(article) {

  var tableStart = `
    <h2>Liste des articles</h2>
    <form id="formtable">
    <table>
      <tr>
        <th>ID</th>
        <th>Article</th>
        <th>Prix</th>
        <th>Prix-Retour</th>
        <th>Quantitée maximale</th>
        <th>Projet</th>
        <th>Quantitée</th>
      </tr>`;

  var tableEnd = `
    </table>
    <input type="submit">
    </form>`;

  function articlesTemplate(article) {
    return `
          <tr>
            <td>${article.ID}</td>
            <td>${article.Article }</td>
            <td>${article.Prix}</td>
            <td>${article.PrixRetour}</td>
            <td>${article.QuantiteeMaximale}</td>
            <td>${article.Projet}</td>
            <td><input type="number" name="quantity${article.ID}" id="quantity${article.ID}" min="1" max="5"></td>
          </tr>
      `;

  }

  let mctxt=txt.filter(value=>
    value.Projet=="mc");
    document.getElementById("tablemc").innerHTML = `
      ${tableStart}
      ${mctxt.map(articlesTemplate).join("")}
      ${tableEnd}
      `;
    ;
}

function processForm(article) {
  var form = document.getElementById('formtable');
  var quantity = document.getElementById([`quantity${article.ID}`]);

  form.onsubmit = function(e) {
   e.preventDefault();
   console.log(quantity);
 };
}

当我记录数量变量时,它返回null。关于如何解决此问题的任何想法?

0 个答案:

没有答案