簡體   English   中英

我可以通過 object 作為 onClick function 的參數嗎

[英]Can I pass an object as the parameter for an onClick function

I am currently trying to create an onclick event for a button that calls a separate function and passes uses an object as the parameter for this function.

我的代碼如下所示:

async function getJourneyAwait(){
  const routes = await getJourney();
  var innerHTML = " "; 
  if(!(routes === null)) {
    for (var i = 0; i < routes.length; i++){
        console.log(routes[i])
        console.log(typeof(routes[i]))
        var route = routes[i]
        innerHTML += '<p> Route ' + i+1 + ': <button onClick=startJourney(' + route + ')>Start Trip</button></p>'
    }
    document.getElementById('tripmessage').innerHTML = innerHTML;
  }
}


function startJourney(route){

    console.log(route);
}

當我嘗試單擊 Start Trip 按鈕時,我收到一條錯誤消息:Uncaught SyntaxError: Unexpected end of input at.(index):1

當我檢查按鈕元素時,參數似乎存在某種錯誤,因為元素如下:

   
<button onclick="startJourney([object" object])="">Start Trip</button>

我嘗試了多種不同的方法,在某些情況下,我能夠讓 function 運行,但是當我執行所有記錄到控制台的操作時,這些都是未定義的。 例如,如果我刪除“路由”兩側的加號和引號,function 會運行,但 undefined 會記錄到控制台。

您看到的[object object]是將您的route object 轉換為字符串格式的結果。

我建議以下兩種方法之一:

  1. Create the button element using createElement , assign the startJourney function to the onclick property using button.onclick = function() { createJourney(route) ]} and append it to the parent element.
  2. 向按鈕元素添加 id 並使用addEventListener("click", createJourney(route))添加點擊事件監聽器

編輯:正如@Teemu 所指出的,如果您使用選項#1,則必須將var i = 0替換為let i = 0因為在具有基於 let 的索引的循環中,通過循環的每次迭代都將具有帶有循環 scope 的新變量 i。

您應該建議您使用Data 屬性並以這種方式綁定您的按鈕:

 function getJourneyAwait(){ const routes = getJourney(); var innerHTML = " "; if(routes) { for (var i = 0; i < routes.length; i++){ var route = routes[i] innerHTML += '<p> Route ' + route + ': <button onclick="startJourney(this)" data-route="' + route + '">Start Trip</button></p>' } document.getElementById('tripmessage').innerHTML = innerHTML; } } function getJourney(){ return [1, 2, 4, 6] } function startJourney(element){ console.log(element.dataset.route); }
 <div id="tripmessage"></div> <button onclick="getJourneyAwait()">GetJourney</button>

暫無
暫無

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

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