簡體   English   中英

將字符串數組傳遞給字符串文字中的 function

[英]Passing array of strings to a function in a string literal

當我將字符串數組和索引傳遞給 onclick 事件時,回調 function 從數組的前兩個值接收參數作為數字而不是數組和索引。

我嘗試使用 Array.from function 將其轉換為數組。

 let presentantes = ["28411", "199904", "214966", "16226"]; console.log('presentantes', presentantes); //presentantes (4) ["28411", "199904", "214966", "16226"] let id = 1 let listNominated = `<li onClick="cargaPresentantes(${presentantes}, ${i})">` function cargaPresentantes(presentantes, id) { console.log('presentantes', presentantes); console.log('id', id) //presentantes 28411 //id 199904 }

我期待得到一個數組["28411", "199904", "214966", "16226"]和索引 1

您不能以這種方式傳遞參數……您應該創建一個“onclick 偵聽器函數”,然后將其關聯到“li”元素。

實際上模板文字的工作原理是這樣的 - 如果傳遞給占位符的變量不是字符串(在這種情況下是數組),那么它將它轉換為字符串。 因此,在您的代碼中,listNominate 的值變為“28411,199904,214966,16226,1”,因此它采用前兩個參數,即 28411 和 199904。

正如 Andrea 所說,我必須添加一個 onclcik 監聽器 function。 為此,我必須首先將字符串文字 append 寫入文檔。

暫無
暫無

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

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