簡體   English   中英

按鈕單擊應將項目添加到數組,但每次 function 調用時數組為空

[英]Button click should add items to array, but array is empty on each function call

代碼看起來像這樣

let sectionWithLimitItems = [];

function addItems(productId) {
     sectionWithLimitItems.push(productId)
}

<button onclick='appendItems({{ productId }})'>Click Me</button>

使用液體,Shopify 的主題模板語言,但不確定這是否會造成復雜性。 如果我每次調用 function 時都記錄數組,那么在 function 開始后它是空的,並且可以看到添加了 id,但在單擊下一個按鈕時數組再次為空。 有任何想法嗎?

- 編輯 - 對不起大家的錯誤。 我確實有 arr,推入我的代碼。 不是 append。 我發帖的時候思路不正確。 sectionWithLimitItems.push(productId) 仍然有同樣的問題

在 javascript 中,您不使用Array.append() ,而應使用Array.push()MDN 參考)。

我想你可能正在尋找Array.push()

const sectionWithLimitItems = [];

function appendItems(productId) {
    sectionWithLimitItems.push(productId)
}

<button onclick='appendItems({{ productId }})'>Click Me</button>

對於Arrays data結構,您可以使用push()方法在Array的末尾添加。 有關更詳細的說明,請查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

let sectionWithLimitItems = [];

function appendItems(arr,item) {
  arr.push(item)
}

console.log(sectionWithLimitItems)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM