简体   繁体   English

在JScript中添加事件处理程序

[英]Add Event Handler in JScript

In the function, editCell() , which is called in response to an onclick event of an HTML table cell, I am trying this: 在函数editCell() ,它响应HTML表格单元格的onclick事件而被调用,我正在尝试这样做:

    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: 在表格底部创建一个新的1单元格行,其中的新单元格就像是使用以下命令创建的:

    ...
    <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). 但是onclick不会被提高(或者函数ref不会响应)。

A co-worker says to use: 一位同事说要使用:

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

but it seems that "...(this)..." will refer to the running context. 但似乎“ ...(this)...”将指向运行上下文。

What is the right way to add a function the takes an argument, to a newly-created cell reference in JScript? 将带有参数的函数添加到JScript中新创建的单元格引用的正确方法是什么?

Must work as far back as IE 8, but only needs to target IE. 必须工作到IE 8,但只需要定位IE。

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

Or in older IE versions: 或在较旧的IE版本中:

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

This explains why using addEventListener is better than onclick . 解释了为什么使用addEventListener优于onclick

.setAttribute("onclick","editCell(this);");

this will refer to newCell. 这将引用newCell。 However, you are trying to call the wrong function (editIt instead of editCell) 但是,您正在尝试调用错误的函数(editIt而不是editCell)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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