通过函数将事件分配给单元格

时间:2017-05-05 04:33:13

标签: javascript html

我试图理解为什么我可以向单元格添加某些项目,例如“id”,而不是其他项目,例如onclick。我的目标是按下一个按钮,向表中添加一行(可以工作) - 并在生成/附加到表上的值上设置一些值。我注意到我可以进入控制台并执行:

rows [row _#]。cells [cell _#]。id ='foo';

并将其显示在和函数的表中;但以下内容不会出现在:

rows [row _#]。cells [cell _#]。onclick ='callEvent(this)';

我应该以不同的方式分配吗?

<button type="button" id="btn_add_row" onclick="addRow()">Add Row</button>
<table class="table table-hover" id="sample_table">
    <thead>
        <th>Column A</th>
        <th id='calculate'>Column B</th>
    </thead>
    <tbody>
        <tr>
            <td>Item 1</td>
            //sample of the td I'd like the function to generate
            <td id='calculate' onclick='callEvent(this)'>Item 2</td>
        </tr>
    </tbody>
</table>


<script type="text/javascript">
// Code to add a row to the table and assign properties to new row
function addRow() {
    var table = document.getElementById("sample_table");
    var lastRow = table.length;
    var numberOfCols = table.rows[0].cells.length;
    var row = table.insertRow(lastRow);
    for (var i=0;i<numberOfCols;i++) {
        row.insertCell(i);
        if (table.rows[0].cells[i].id === 'calculate') {
// The calculate id will appear on the TD after running
            table.rows[i].id = 'calculate';
// The onclick event will not appear on the TD afer running
            table.rows[i].onclick='callEvent(this)';
        }

function callEvent(element) {
                console.log('Calculate event fired!');
}
</script>

3 个答案:

答案 0 :(得分:1)

最大的问题是您没有向onclick属性提供回调函数引用。您正在提供一个字符串:

.onclick='callEvent(this)'

因此,click事件发生时,实际上不会调用任何函数。

接下来,您不应该在JavaScript中使用事件属性(例如onclick),或者根本不需要添加内联HTML事件处理属性(该技术大约需要20年):

  1. 创建&#34;意大利面条代码&#34;这很难阅读和调试。
  2. 导致代码重复。
  3. 不要好好扩展
  4. 请勿遵循 separation of concerns 开发方法。
  5. 围绕属性值创建匿名全局包装函数,这些函数会改变回调函数中的this绑定。
  6. 请勿关注 W3C Event Standard
  7. 相反,请在JavaScript中完成所有工作并使用 .addEventListener() 设置事件处理程序。

    另外(FYI)id属性必须是唯一的,因此当您创建新的行或单元格时,请不要重复使用已分配的id

    以下是一个例子:

    &#13;
    &#13;
    // Place all of this inside of a <script> element that is just before the 
    // closing of the body (</body>)
    
    // Get references to all elements that you'll be working with
    var btnAddRow = document.getElementById("btn_add_row");
    var tbl = document.getElementById("sample_table");
    
    // Now, set up the event handling functions
    btnAddRow.addEventListener("click", addRow);
    
    // Code to add a row to the table and assign properties to new row
    function addRow() {
        var counter = 1; // id attributes must be unique. This will keep it that way.
        var numberOfCols = tbl.rows[0].cells.length;
        var row = tbl.insertRow();
        for (var i = 0; i < numberOfCols; i++) {
            var cell = row.insertCell(i);
            cell.id = "row" + (tbl.rows.length - 1) + "cell" + counter;  
            
            // Now, we'll create a new button, place that button in the new cell and
            // set up a click event handler for it.
            var btn = document.createElement("button");
            btn.textContent = cell.id;
            btn.id = "btn" + tbl.rows.length + counter;
            
            // Add a click event handler 
            btn.addEventListener("click", function(){
                alert("You clicked cell: " + this.id);
            });
            
            // And now include the button in the cell
            cell.appendChild(btn);
            
            counter++;  // Increment the counter after using it
        }
    }
    &#13;
    td { border:1px solid black; }
    
    td:nth-child(2) { cursor:pointer; }
    &#13;
    <button type="button" id="btn_add_row">Add Row</button>
    <table class="table table-hover" id="sample_table">
        <thead>
            <th>Column A</th>
            <th id='calculate'>Column B</th>
        </thead>
        <tbody>
            <tr>
                <td>Item 1</td>
                <!-- sample of the td I'd like the function to generate -->
                <td id='calculate'>Item 2</td>
            </tr>
        </tbody>
    </table>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

两件事:

onclick需要一个函数。所以要解决你的问题,改变

 table.rows[i].onclick='callEvent(this)';

 table.rows[i].onclick=callEvent;

第二件事是,事件的参数实际上是事件,而this是指元素:

function callEvent(event) {
     console.log('Calculate event fired!');
     // "event" is the event
     // "this" is the element
}

答案 2 :(得分:-1)

missing need to second bracket end and use this callEvent(this) without single inverted comma.

Like this...

<script type="text/javascript">
// Code to add a row to the table and assign properties to new row
function addRow() { 
    var table = document.getElementById("sample_table");
    var lastRow = table.length;
    var numberOfCols = table.rows[0].cells.length;
    var row = table.insertRow(lastRow);
    for (var i=0;i<numberOfCols;i++) {
        row.insertCell(i);       
        if (table.rows[0].cells[i].id === 'calculate') {
// The calculate id will appear on the TD after running
            table.rows[i].id = 'calculate';
// The onclick event will not appear on the TD afer running
            table.rows[i].onclick=callEvent(this);
        }
    }
}
function callEvent(element) {
                console.log('Calculate event fired!');
}
</script>