Javascript - 在分配时执行的监听器

时间:2015-12-18 06:49:02

标签: javascript

所以,我正在开发一个HTML页面,该页面显示一个表格,其中包含一个可编辑的文本框和一个列表中每个引号的行的删除按钮。该列表是从存储的文件中获取的,因此我需要在每次获取时动态生成此表及其行。但是,当此代码运行时,生成的表为空,因为添加侦听器时,删除行函数会执行,并在添加后立即删除该行。

    for (var i = 0; i < quotesArray.length; i++) {
      //Insert a new row into the table.
      var newQuoteRow = quoteList.insertRow(-1);
      var cellOne = newQuoteRow.insertCell(0);
      var cellTwo = newQuoteRow.insertCell(1);

      //Insert editable text boxes for a quote into the row.
      var quoteInput = document.createElement('input');
      quoteInput.value = quotesArray[i];
      quoteInput.className = "quote";
      cellOne.appendChild(quoteInput);

      //Put a delete button at the end of the row.
      var deleteQuoteButton = document.createElement('button');
      deleteQuoteButton.innerHTML = "x";
      cellTwo.appendChild(deleteQuoteButton);
      deleteQuoteButton.addEventListener('click', deleteCurrentQuoteRow(deleteQuoteButton));
    }


  });
}

function deleteCurrentQuoteRow(buttonToDelete) {
  var currentRow = buttonToDelete.parentNode.parentNode; //get the grandparent node, which is the row containing the cell containing the button.
  currentRow.parentNode.removeChild(currentRow); //delete the row in the table
}

据我所知,出现此问题是因为addEventListener方法中链接的函数有一个参数,导致它立即执行而不是等待单击。但是,我想不出一种方法来实现它,而不将按钮被单击作为参数,因为那时我不知道要删除哪一行。我该如何解决这个问题,以便实际填充表格,删除按钮实际上会删除一行?

1 个答案:

答案 0 :(得分:1)

目前,您正在调用函数deleteCurrentQuoteRow并将其返回值undefined指定为事件侦听器。

使用

deleteQuoteButton.addEventListener('click', function(){
    deleteCurrentQuoteRow(this); //Here this refers to element which invoke the event
});

或者,您可以将函数deleteCurrentQuoteRow修改为

function deleteCurrentQuoteRow() {
  var currentRow = this.parentNode.parentNode; //get the grandparent node, which is the row containing the cell containing the button.
  currentRow.parentNode.removeChild(currentRow); //delete the row in the table
}

然后您可以将函数引用传递为

deleteQuoteButton.addEventListener('click', deleteCurrentQuoteRow);