【发布时间】:2017-11-10 16:17:38
【问题描述】:
我正在创建一个包含多个表的应用,其中一个包含客户及其位置,而另一个包含客户及其库存商品和商品 ID。我在创建可用于多个表的函数时遇到问题,该函数允许用户为表创建新行,并且我有工作代码,但使用该代码我必须为每个唯一表复制它。
我想要的是使用 (this) 以便单个函数适用于多个表,我曾尝试使用 (this) 但它显然无法正常工作,第一个问题是它无法读取属性“长度”对于桌子,但我相信我会遇到更多问题。
任何帮助将不胜感激。
期望结果:使用 (this) 在多个表上使用一个函数。
function appendRow() {
var table = document.getElementsByTagName('table'); // table reference
length = this.length,
row = this.insertRow(this.rows.length), // append table row
i;
// insert table cells to the new row
for (i = 0; i < this.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
// this works, but if I want it for multiple tables, I must copy it for each table....
/*
function appendRow() {
var custList = document.getElementById('custList'), // table reference
row = custList.insertRow(custList.rows.length), // append table row
i;
// insert table cells to the new row
for (i = 0; i < custList.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
*/
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
<div id="custDiv">
<div class="addBtns">
<input id="searchName" onkeyup="custSearchName()" type="text" placeholder="search name"></input>
</div>
<div style="width: 355px; margin: 0 auto; height: 50px;">
<button id="addCust" onclick="appendRow(this)">add customer</button>
</div>
<div class="custScroll">
<table id="custListTop" contenteditable="false">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>something</td>
</tr>
</table>
</div>
</div>
【问题讨论】:
-
为什么不定义一个通用的
function appendRow(id) { var custList = document.getElementById(id)... }? -
在
length = this.length中,当你真正想要table中的表数时,为什么要使用this(即window)? (What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?) -
附注:
<input>是一个自闭合标签,所以它应该写成<input ... />而不是<input ...></input>- 或者你可以在使用正确的 HTML 时完全省略结束斜杠文档类型。 -
如果你真的想和
this一起使用这个功能,你可以开始把var table = document.getElementsByTagName('table');这行去掉,这样就没用了。然后你必须在调用之前检索表并使用call将它绑定到函数的this,就像这样:var table1 = document.getElementById('custList'); appendRow.call(table1);
标签: javascript html function html-table this