![](/img/trans.png)
[英]passing html tags arguments in django template to javascript function
[英]Syntax error while passing arguments to JavaScript function from Django template
我必須將 Django 模板中的 4 個參數傳遞給 JavaScript 函數。 在這 4 個中,3 個是整數/小數,1 個是字符串。
<button onclick="addCart({{ item.id }}, {{ item.price }}, {{ item.discount }}, {{item.name}})">
Add to cart
</button>
這是 Javascript 函數。
let USER_CART = [];
function addCart(itemId, itemPrice, itemDiscount, itemName) {
let itemQuantity = parseInt(document.getElementById(itemId).value);
if (itemQuantity > 0) {
let item_index = USER_CART.findIndex(item => item.id === itemId);
if (item_index === -1) {
let item = {
id: itemId,
price: itemPrice,
discount: itemDiscount,
quantity: itemQuantity,
title: itemName,
};
USER_CART.push(item);
} else {
USER_CART[item_index].quantity += itemQuantity;
}
}
}
每當我單擊按鈕時,此錯誤都會顯示在控制台上。
SyntaxError: missing ) after argument list
另一個有趣的事情是,如果我從代碼中完全刪除item.name
和itemName
,它就可以正常工作。
您需要在{{item.name}}
周圍添加引號。
<button onclick="addCart({{ item.id }}, {{ item.price }}, {{ item.discount }}, '{{item.name}}')">
Add to cart
</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.