简体   繁体   中英

Can't pass a variable as an argument in a onClick function

I want to have a table and its cells are filled with data from MySQL.

The table have many TDs, which have an Id.

I want to pass the id of the cell to a function, so that I can edit its content:

document.getElementById(IndexedActionButton).innerHTML = '<input type="Button" name = "EditActionButton" id="EditActionButton" onClick="SaveUpdateToActionList(&quot;Cell_ID&quot;)" value="Edit Action" />';

function SaveUpdateToActionList(Cell) {
    alert(Cell);   
    document.getElementById(Cell).innerHTML = 'Here'; 
}

When I have alert(Cell); displayed, I see this sends the Text "Cell_ID", whereas I wanted to see the data ActionButton386 there.

Any help appreciated.

You can pass in the element being clicked by setting your onClick script to SaveUpdateToActionList(this);

Then, in the body of SaveUpdateToActionList , Cell will refer to the button that just got clicked. You can then walk up the DOM to get to the TD it belongs to.

You can try this:

   document.getElementById(IndexedActionButton).innerHTML = '<input type="Button" name =      "EditActionButton" id="EditActionButton" onClick="SaveUpdateToActionList()" value="Edit Action" />';

   function SaveUpdateToActionList(event) {
    alert(event.target.id);   
    document.getElementById(Cell).innerHTML = 'Here'; 
   }

But if i understand correctly what you are trying to do, you shoud have a single event listner that catches bubling events from all cells, rather that attaching a an onclick to each cell....

Just register the event listener separately from specifying the innerHTML property:

Document.getElementById(IndexedActionButton).addEventListener('onclick', SaveUpdateToActionList);

SaveUpdateToActionList will be called with an event object as the first argument. You can access which element was clicked by checking the event.target property. For more information check out MDN - addEventListener documentation

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