简体   繁体   中英

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.

My code can be seen below:

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);
}

When I try to click the Start Trip button I get an error stating: Uncaught SyntaxError: Unexpected end of input at.(index):1

When I inspect the button element it there seems to be some kind of error with the parameter as the element is as follows:

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

I have tried multiple different ways and in some cases I have been able to get the function to run but when I do all that is logged to the console is undefined. For example, if I remove the plus signs and quotes on either side of 'route' the function runs but undefined is logged to the console.

The [object object] that you are seeing is the result of the conversion of your route object to a string format.

I suggest one of two approaches:

  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. Add an id to the button element and add a click event listener using addEventListener("click", createJourney(route))

Edit: As pointed out by @Teemu, in case you use option #1, you'll have to replace var i = 0 by let i = 0 since in a loop with a let-based index, each iteration through the loop will have a new variable i with loop scope.

You should I would recommend you use Data attributes and also bind your buttons this way:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM