Search code examples
javascriptonclickprototypejsdom-events

Changing an onclick() inside onclick()


I have a TABLE and each TABLEROW has a div in it with the onclick deleteRow(rowIndex), where rowIndex is the index of the row that was supposedly clicked on. The problem is that any time I try to actively change one of the row's onclick like this, it freaks out and automatically calls it as soon as I change it:

row.onclick = deleteRow(rowIndex);

I am also using Prototype.js.

Here is my handler:

deleteRow = function(rowIndex) {
    var table = $('tableElmt');
    table.each(function(row, index) {
        if(index == rowIndex)
            row.onclick = deleteRow(index);
    })
}

When I change onclick like that, it calls deleteRow again instantly and goes into a loop and I cant figure out why.

I think it has something to do with the way I call deleteRow() inside deleteRow(), although it could also be that I am changing 'onclick' incorrectly.

I have also tried this to handle clicks on the table rows:

row.observe('click', deleteRows(rowIndex));

But it does the same thing. Also, this conflicts with the onclick() event handler that already exists for all the rows in the html and I'm not sure how to handle that.

How do I change an onclick() event handler inside that onclick() event handler?


Solution

  • You are calling the deleteRow function, and assign it's result to the onclick handler. What you are trying to achieve is:

    row.onclick = (function(index){
     return function(){
       deleteRow(index);
     }
    })(index);