所以这应该很简单,但它似乎让我绊倒。我在表格的单元格中有一个下拉菜单。当该值更改时,我调用一个 javascript 函数并在该函数中传递该下拉列表。我如何从中获取表格?示例代码:
<table><tr>
<td>DATA</td>
<td><select id='leadState' onChange='updateData(this)'><option selected='selected' value='new'>New</option><option value='old'>Contacted</option></select></td>
</tr>
</table>
JavaScript:
function updateData(select) {
var table = select.parentNode.parentNode.parentNode;
var row = select.parentNode.parentNode;
var cell = select.parentNode;
}
为什么这不能正确返回表格?
最佳答案
因为您忘记了 tbody
元素(该元素是可选的,但大多数(如果不是全部)浏览器都会添加到 table
包装 tr
元素。尝试另一个 parentNode
:
function updateData(select) {
// select -> td -> tr -> tbody -> table
var table = select.parentNode.parentNode.parentNode.parentNode;
var row = select.parentNode.parentNode;
var cell = select.parentNode;
}
而且您实际上不必为每个变量遍历表
:
function updateData(select) {
var td = select.parentNode,
tr = td.parentNode,
tbody = tr.parentNode,
table = tbody.parentNode;
}
假设您想坚持使用纯 JavaScript,并且不希望在检索元素时手动迭代 DOM,下面是 closest()
的简单纯 JavaScript 实现:
HTMLElement.prototype.closest = function (selector) {
var self = this.length ? this[0] : this;
while (self.tagName.toLowerCase() !== selector.toLowerCase() && self.tagName.toLowerCase() !== 'body') {
self = self.parentNode;
}
return self.tagName.toLowerCase() == 'body' ? this : self;
}
function updateData(select) {
var td = select.closest('td'),
tr = select.closest('tr'),
table = select.closest('table');
console.log(td, tr, table);
}
关于javascript - 从单元格数据中获取表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17433353/