簡體   English   中英

從單元格數據中獲取表格

[英]Get the table from cell data

所以這應該很簡單,但它似乎讓我磕磕絆絆。 我在桌子的一個單元格中有一個下拉列表。 當該值改變時,我調用一個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;
}

JS小提琴演示

而且你真的不需要為每個變量遍歷table

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

JS小提琴演示

假設您希望堅持使用純JavaScript,並且不希望在檢索元素時手動迭代DOM,這里是一個簡單的plain 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);
}

JS小提琴演示

大衛托馬斯的答案可能是最好的答案。 雖然如果你的頁面上有jQuery,你也可以使用'nearest()'函數。

$(select).closest('table')

這將考慮自動添加tbody容器的瀏覽器和不添加tbody容器的瀏覽器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM