0

So this should be pretty simple, but it seems to be making me stumble. I have a drop down in a cell in a table. When that value is changed, I call a javascript function and pass that drop down in the function. How do i get the table from that? example code:

<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;
}

Why does this not return the table properly?

4

2 回答 2

1

大卫托马斯的答案可能是最好的答案。虽然如果您的页面上有 jQuery,您也可以使用“closest()”函数。

$(select).closest('table')

这将解释自动添加 tbody 容器的浏览器和不自动添加容器的浏览器。

于 2013-07-02T18:53:13.047 回答
1

因为您忘记了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;
}

JS 小提琴演示

而且你真的不必遍历每个table变量:

function updateData(select) {
    var td = select.parentNode,
        tr = td.parentNode,
        tbody = tr.parentNode,
        table = tbody.parentNode;
}

JS 小提琴演示

假设您想坚持使用纯 JavaScript,并且不希望在检索元素时手动遍历 DOM,这里有一个简单的纯 JavaScript 实现closest()

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);
}

JS 小提琴演示

于 2013-07-02T18:47:11.753 回答