【发布时间】:2020-10-12 14:26:46
【问题描述】:
我的目标是打印字符串,并为每个字符串打印一个按钮。这个按钮需要一个 onclick="add()"。
+"<button onclick=add("+carrello[i].nome+","+carrello[i].quantita+");>+</button>"+
我在 read() 函数中调用外部函数时遇到问题。我需要声明一个使用 onclick 函数并调用 add() 的按钮,但是当我运行代码时会发生这种情况。
function add(nome, prezzo)
{
var exist = 0;
var prodotto = new Object();
prodotto.nome=nome;
prodotto.costo=prezzo;
prodotto.quantita=1;
for (i = 0; i < carrello.length; i++)
{
if(carrello[i].nome==prodotto.nome)
{
//esiste già
exist = 1;
carrello[i].quantita=carrello[i].quantita+1;
$(event.target).closest('tr').find('.qty').html(" (x"+carrello[i].quantita+")");
}
}
if(exist == 0)
{
$(event.target).closest('tr').find('.qty').html(" (x1)");
carrello.push(prodotto);
}
read();
}
function read()
{
var totale = 0;
document.getElementById("demo").innerHTML = "";
for (i = 0; i < carrello.length; i++)
{
document.getElementById("demo").innerHTML += carrello[i].nome+"x"+carrello[i].quantita+" <button onclick=add("+carrello[i].nome+","+carrello[i].quantita+");>+</button>"+"<br>";
//document.getElementById("demo").innerHTML = ;
var x = document.createElement("HR");
document.getElementById("demo").appendChild(x);
document.getElementById("ordine").value = document.getElementById("demo").innerHTML;
totale = totale + carrello[i].costo * carrello[i].quantita;
document.getElementById("totale").innerHTML = "Totale: "+totale+"€";
}
if(carrello.length==0)
{
totale = 0;
document.getElementById("totale").innerHTML = "";
}
document.getElementById("tot").value = totale;
}
【问题讨论】:
-
根据您提供的内容,这些函数都没有被调用过。我已将您的代码添加到可运行的 sn-p 中。请编辑它以反映minimal reproducible example
-
复制整个算法没用,我只想知道如何在另一个函数中的 onclick 中调用函数。
-
好吧,如果我们没有可复制的示例,那么尝试帮助您解决问题是没有用的。你必须明白,我们无法直观地知道发生了什么。您没有具体说明您遇到的实际错误,只是什么都没有发生。有一个调试工作,你应该做的,如果没有合适的例子,我们也做不到。
-
你也许/可能想要
" <button onclick='add(" .. ");'>+</button>"- 但这只是猜测。为什么不添加委托事件处理程序而不是过时的onclick=?但是nome看起来可能是“名称”,因此如果名称中有空格,则需要将其放在引号中。 -
阅读minimal reproducible example - 强调重现问题的最少代码 - 究竟是什么问题?是否使用带有按钮的
innerHTML +=?然后你就不需要所有其他代码了。是nome有一个空格并且它破坏了你的 HTML 吗?那么您不需要所有其他代码,但您确实需要nome的示例。我们不想要“整个算法”,只需要足够演示问题而无需猜测。
标签: javascript html jquery button onclick