简体   繁体   中英

javascript dynamic button click event

I'm making a dynamic button for each for in a table to delete. I make the button id have the key to the row so I can query it on click to know which one to delete. Since I'm assigning all buttons the same function I need to pass the button that was clicked to the event handler so I can query the id from inside the event handler.

When hardcoding I'd just pass 'this' to the event handler. How do I do this when making a dynamic button?

Right now I have:

{
var cell0 = row.insertCell(0);
var btn = document.createElement("input");
btn.type = "button";
btn.id = "btnHistorySelect_" + roundHdr[i].id;              // append the id to the name so we can get it when select button is clicked so we know what round to select as current
btn.value = "Set Current";
btn.onclick = btnHistorySelect;
cell0.appendChild(btn);
}


function btnHistorySelect() {
}

The event handler gets called, but I have no idea what button made the click.

You can use the this.id or event.target.id attribute to get the id of the button that initiated the event.

function btnHistorySelect(event) {

    var id = this.id;

         or
   // var elem = event.target;
   // var id = elem.id

}

Because you are assigning the function reference , the this inside the function corresponds to the current element is question.

function btnHistorySelect(event) {
   alert(event.target); // Will alert the actual element clicked.
}

如果您使用此功能,则无需知道或分配ID

HTML输入按钮元素在btnHistorySelect函数中通过this变量可用。

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