2017-05-05 15 views
0

セルに特定のアイテム(「id」など)を追加でき、onclickなどのアイテムを追加できない理由を理解しようとしています。私の目標は、テーブルに行を追加するボタンを押したままにして、テーブルに生成/追加された値を設定することです。私はコンソールにステップインして、次のようにすることができることに気づいた。​​セルに関数を介してイベントを割り当てる

行[行_#]。セル[セル_#]。id = 'foo';

これは、と関数の表に表示されています。しかし、以下は表示されません:

行[行_#]。セル[セル_#]。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> 
+0

は、文字列の上に追加しようとしている 'onclick'のですか?これは関数でなければなりません。 'onclick = callEvent'を試してください。 – Jorg

答えて

1
:だから二つ目は、イベントのパラメータは、実際にイベントであり、そして this要素を指し、ある

table.rows[i].onclick=callEvent; 

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

を変更、あなたの問題を解決するために

最大の問題は、onclickプロパティにコールバック関数リファレンスを提供していないことです。 clickイベントが発生したときに

.onclick='callEvent(this)' 

だから、何の機能が実際に呼び出されません取得します:あなたは、文字列を供給しています。

次に、あなたは彼らのように(その技術はおよそ20歳)あなたのJavaScriptでのイベントプロパティ(のようonclick)を使用して、またはすべての属性を扱うインラインHTMLイベントを追加すべきではありません。

  1. は、「作成しますスパゲッティコード "を読み込み、デバッグすることは困難です。
  2. コードの複製につながります。
  3. separation of concerns開発方法論に従わないでも
  4. をスケーリングしないでください。
  5. コールバック関数のthisバインドを変更する属性値のまわりに匿名グローバルラッパー関数を作成します。
  6. W3C Event Standardに従わないでください。

代わりに、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>

+0

私はフィードバックと、なぜそのように行を追加するべきではないのかを感謝します。しかし、問題の目的は、行の追加ボタンをクリックした後、新しい行の特定のセルにイベントをバインドする方法です。 –

+0

@jeffmクリックイベントハンドラが各新しい行の最後のセルに追加されたことを示すために私の答えを更新しました。 'onclick'を使用せず、より標準的な' .addEventListener() 'を使用するので、このプロセスは簡単に動作します。コードは 'this'をコールバックに渡そうとしません(' this'は常に同じオブジェクトを指すわけではないかもしれません)。また、コールバックは文字列として提供されるのではなく、実際の関数参照。 –

+0

説明に時間を割いてくれてありがとう、私はあなたの応答からかなり学んだ。 –

0

2つのこと:

onclickは、機能を期待しています。

function callEvent(event) { 
    console.log('Calculate event fired!'); 
    // "event" is the event 
    // "this" is the element 
} 
-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> 
+0

'table.rows [i] .onclick = callEvent(this);'が間違っています。これは 'callEvent'関数を直ちに呼び出し、その関数からの戻り値が何であれ(この例では何もありません)、' onclick'プロパティの値になります。 'onclick'を使うつもりならば、' .addEventListner() 'を使うべきではありません)、行は' 'table.rows [i] .onclick = function(){callEvent (この); } '。 –

関連する問題