表中的querySelector

时间:2017-08-10 16:36:32

标签: javascript html google-chrome google-chrome-extension jquery-selectors

我有这个简单的chrome扩展,允许用户创建一个表但是我无法绑定删除按钮。

options.html

<body>
<!-- would be created as the user clicks on new Row -->
<table id="rows">
  <tr id="row0"> 
    <td>
      <input id="textBox" type="text">
      <button id="remove">Remove</button>
    </td>
 </tr>
</table>

<!-- used as template -->
<table hidden>
  <tbody>
    <tr id="rowTemplate">
      <td>
        <input id="textBox" type="text">
        <button id="remove">Remove</button>
      </td>
    </tr>
  </tbody>
</table>
<button id="newRow">new Row</button>
<script src="options.js"></script>

options.js

function Row() {
  var rows = document.getElementById('rows');
  this.node = document.getElementById('rowTemplate').cloneNode(true);
  this.node.id = 'row' + (Row.next_id++);
  this.node.row = this;
  rows.appendChild(this.node);
  this.node.hidden = false;

  var row = this;
  this.getElement('remove').onclick = function () {
    row.node.parentNode.removeChild(row.node);
  }
}

Row.next_id = 0;
Row.prototype.getElement = function (name) {
  return document.querySelector('#' + this.node.id + ' .' + name);
}
window.onload = function() {
  document.getElementById('newRow').onclick = function() {
    new Row();
  };
}

问题在于 querySelector ,因为无论何时点击“新行”,我都会收到错误Uncaught TypeError: Cannot set property 'onclick' of null,指向调用getElement('remove').onclick的{​​{1}}其中querySelector返回null。

0 个答案:

没有答案