通过函数将事件分配给单元格(Assigning an event to a cell via a function)

我试图理解为什么我可以将某些项目添加到单元格中,例如'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>

I'm trying to understand why I can add certain items to a cell, such as 'id', and not other items such as an onclick. My goal is to have a button pressed, which adds a row to a table (which works) - and set some values on the that is generated/appended to the table. I've noticed that I can step into the console and do:

rows[row_#].cells[cell_#].id = 'foo';

and have it appear in the table on the and function; but the following will not appear on the :

rows[row_#].cells[cell_#].onclick = 'callEvent(this)';

Should I be assigning this differently?

<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>

最满意答案

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

.onclick='callEvent(this)'

所以,当发生click事件时,实际上没有函数被调用。

接下来,您不应该在您的JavaScript中使用事件属性(如onclick ),或者根本不添加内联HTML事件处理属性(该技术大约有20年历史),因为它们是:

创建难以阅读和调试的“意大利面代码”。 导致代码重复。 不要很好地扩展 不要按照关注发展方法的分离 。 围绕您的属性值创建匿名全局包装函数,以改变回调函数中的this绑定。 不要遵循W3C事件标准

相反,在JavaScript中完成所有工作并使用.addEventListener()来设置事件处理程序。

另外(FYI) id属性需要是唯一的,所以当你创建一个新的行或者单元时,不要重用已经分配的id 。

这是一个例子:

// 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
    }
} 
  
td { border:1px solid black; }

td:nth-child(2) { cursor:pointer; } 
  
<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> 
  
 

The biggest issue is that you are not supplying a callback function reference to your onclick property. You are supplying a string:

.onclick='callEvent(this)'

So, no function actually gets invoked when the click event occurs.

Next, you shouldn't be using event properties (like onclick) in your JavaScript or adding inline HTML event handling attributes at all (that technique is about 20 years old) as they:

Create "spaghetti code" that is difficult to read and debug. Lead to duplication of code. Don't scale well Don't follow the separation of concerns development methodology. Create anonymous global wrapper functions around your attribute values that alter the this binding in your callback functions. Don't follow the W3C Event Standard.

Instead, do all your work in JavaScript and use .addEventListener() to set up event handlers.

Also (FYI) id attributes need to be unique, so when you create a new row or cell, don't reuse an already assigned id.

Here's an example:

// 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
    }
} 
  
td { border:1px solid black; }

td:nth-child(2) { cursor:pointer; } 
  
<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> 
  
 

通过函数将事件分配给单元格(Assigning an event to a cell via a function)

我试图理解为什么我可以将某些项目添加到单元格中,例如'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>

I'm trying to understand why I can add certain items to a cell, such as 'id', and not other items such as an onclick. My goal is to have a button pressed, which adds a row to a table (which works) - and set some values on the that is generated/appended to the table. I've noticed that I can step into the console and do:

rows[row_#].cells[cell_#].id = 'foo';

and have it appear in the table on the and function; but the following will not appear on the :

rows[row_#].cells[cell_#].onclick = 'callEvent(this)';

Should I be assigning this differently?

<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>

最满意答案

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

.onclick='callEvent(this)'

所以,当发生click事件时,实际上没有函数被调用。

接下来,您不应该在您的JavaScript中使用事件属性(如onclick ),或者根本不添加内联HTML事件处理属性(该技术大约有20年历史),因为它们是:

创建难以阅读和调试的“意大利面代码”。 导致代码重复。 不要很好地扩展 不要按照关注发展方法的分离 。 围绕您的属性值创建匿名全局包装函数,以改变回调函数中的this绑定。 不要遵循W3C事件标准

相反,在JavaScript中完成所有工作并使用.addEventListener()来设置事件处理程序。

另外(FYI) id属性需要是唯一的,所以当你创建一个新的行或者单元时,不要重用已经分配的id 。

这是一个例子:

// 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
    }
} 
  
td { border:1px solid black; }

td:nth-child(2) { cursor:pointer; } 
  
<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> 
  
 

The biggest issue is that you are not supplying a callback function reference to your onclick property. You are supplying a string:

.onclick='callEvent(this)'

So, no function actually gets invoked when the click event occurs.

Next, you shouldn't be using event properties (like onclick) in your JavaScript or adding inline HTML event handling attributes at all (that technique is about 20 years old) as they:

Create "spaghetti code" that is difficult to read and debug. Lead to duplication of code. Don't scale well Don't follow the separation of concerns development methodology. Create anonymous global wrapper functions around your attribute values that alter the this binding in your callback functions. Don't follow the W3C Event Standard.

Instead, do all your work in JavaScript and use .addEventListener() to set up event handlers.

Also (FYI) id attributes need to be unique, so when you create a new row or cell, don't reuse an already assigned id.

Here's an example:

// 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
    }
} 
  
td { border:1px solid black; }

td:nth-child(2) { cursor:pointer; } 
  
<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>