gpt4 book ai didi

javascript - 不用 jQuery 查找最近的元素

转载 作者:IT王子 更新时间:2023-10-29 02:46:58 28 4
gpt4 key购买 nike

我试图在没有 jquery 的情况下找到具有特定标签名称的最接近的元素。当我点击 <th>我想访问 <tbody>对于那张 table 。建议?我阅读了有关偏移量的信息,但并没有真正了解太多。我应该只使用:

假设 th 已经设置为点击了 th 元素

th.offsetParent.getElementsByTagName('tbody')[0]

最佳答案

非常简单:

el.closest('tbody')

除 IE 外,所有浏览器均支持。
更新:Edge 现在也支持它。

不需要 jQuery。此外,将 jQuery 的 $(this).closest('tbody') 替换为 $(this.closest('tbody')) 将提高性能,尤其是当元素没有找到。

IE 的 Polyfill:

if (!Element.prototype.matches) Element.prototype.matches = Element.prototype.msMatchesSelector;
if (!Element.prototype.closest) Element.prototype.closest = function (selector) {
var el = this;
while (el) {
if (el.matches(selector)) {
return el;
}
el = el.parentElement;
}
};

请注意,当找不到元素时没有return,当找不到最近的元素时有效地返回undefined

详情请见: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

关于javascript - 不用 jQuery 查找最近的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18663941/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com