0

In the function, editCell(), which is called in response to an onclick event of an HTML table cell, I am trying this:

    var tbl = [valid table ref];
    var row = tbl.insertRow(-1); // insert at end.
    var newCell = row.insertCell(-1);
    newCell.className = "tblItems newItem";
    newCell.innerHTML = "  Click to add a property item...";
    newCell.onclick   = "editCell(this);";

to create a new, 1-cell row at the bottom of the table, where hte new cell is as if it had been created with:

    ...
    <tr>
        <td class="tableItems newItem" onclick="editCell(this);"> 
            &#160;&#160;Click to add a property item...
        </td>
    </tr>
    ...

But the onclick is not being raised (or the function ref doesn't respond when it is).

A co-worker says to use:

    newCell.onclick = function () {
        editIt(this);
    }

but it seems that "...(this)..." will refer to the running context.

What is the right way to add a function the takes an argument, to a newly-created cell reference in JScript?

Must work as far back as IE 8, but only needs to target IE.

Brian Wren
  • 367
  • 5
  • 15

3 Answers3

1
newCell.addEventListener('click', editCell, false);

Or in older IE versions:

newCell.attachEvent('onclick', editCell, false);

This explains why using addEventListener is better than onclick.

Community
  • 1
  • 1
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
0
.setAttribute("onclick","editCell(this);");
Banana
  • 7,424
  • 3
  • 22
  • 43
-1

this will refer to newCell. However, you are trying to call the wrong function (editIt instead of editCell)

newCell.onclick = function () {
    editCell(this);
}
Johan
  • 1,016
  • 7
  • 13
  • The first parameter passed to the onclick function is the event, not the sender. Naming it sender doesn't change that. – James Montagne Mar 13 '14 at 15:22
  • Johan, Is the situation that the 'this' within the parentheses is not evaluated until the referenced function is actually called? – Brian Wren Mar 13 '14 at 15:25
  • @BrianWren when calling a function, the word "this" is a reference to the object that called the function. – Johan Mar 14 '14 at 13:43