我有一个使用 json 数据制作表格的程序。这种技术使用模板 liretals,所以我可以自己添加行。我的问题是我需要从输入中获取数据,该输入具有模板文字作为 id,但 getElementById 不允许我这样做。
我已经尝试过转义我的括号,但这不起作用。我研究过使用一个简单的索引,但我不知道如何在我的函数中设置它。
这是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);
processArticles(txt);
processForm(txt);
}
};
xmlhttp.open("GET","../articles.json",true);
xmlhttp.send();
function processArticles(txt) {
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(txt, index) {
return `
<tr>
<td>${txt.ID}</td>
<td>${txt.Article }</td>
<td>${txt.Prix}</td>
<td>${txt.PrixRetour}</td>
<td>${txt.QuantiteeMaximale}</td>
<td>${txt.Projet}</td>
<td><input type="number" name="quantity${txt.ID}" id="quantity${txt.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}
`;
;
}
问题出在最后一个函数中我的数量的 .getElementById 中。
function processForm(txt) {
var form = document.getElementById('formtable');
var quantity = document.getElementById(`"quantity$\\{txt.ID\\}"`);
form.onsubmit = function(e) {
e.preventDefault();
console.log("HI");
console.log(quantity.value);
};
}
我希望能够收集每个所选对象的数量以及同一对象的价格,以便我可以在表格末尾计算总价。
最佳答案
我认为你不小心引用了@DontVoteMeDown 已经提到的错误。
假设
txt.ID = 2
然后是模板字符串
`<input ... id="quantity${txt.ID}" />`
会导致
<input ... id="quantity2" />
以及选择器的模板字符串
document.getElementById(`quantity${txt.ID}`);
会导致
document.getElementById("quantity2");
所以它应该可以正常工作。
如果您想对结果表的所有输入值求和,您必须选择所有输入并迭代这些值。
var total = 0;
document.querySelectorAll('#formtable input').forEach(function(input) {
total += parseInt(input.value);
})
关于javascript - 使用模板文字作为 id 从输入中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56067545/