我正在尝试查找具有特定标记名但没有jquery的最接近的元素。当我单击一个<th>
时,我想要访问该表的<tbody>
。有什么建议吗?我读过关于offset的文章,但并不是很了解它。我应该只使用:
假设已将th设置为已单击的th元素
th.offsetParent.getElementsByTagName('tbody')[0]
发布于 2014-06-08 23:13:55
在聚会上有点(非常)晚了,但尽管如此。这应该会完成trick
function closest(el, selector) {
var matchesFn;
// find vendor prefix
['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {
if (typeof document.body[fn] == 'function') {
matchesFn = fn;
return true;
}
return false;
})
var parent;
// traverse parents
while (el) {
parent = el.parentElement;
if (parent && parent[matchesFn](selector)) {
return parent;
}
el = parent;
}
return null;
}
发布于 2013-09-07 02:11:06
下面是如何在不使用jQuery的情况下通过标记名获得最接近的元素:
function getClosest(el, tag) {
// this is necessary since nodeName is always in upper case
tag = tag.toUpperCase();
do {
if (el.nodeName === tag) {
// tag name is found! let's return it. :)
return el;
}
} while (el = el.parentNode);
// not found :(
return null;
}
getClosest(th, 'tbody');
发布于 2014-11-18 23:07:19
function closest(el, sel) {
if (el != null)
return el.matches(sel) ? el
: (el.querySelector(sel)
|| closest(el.parentNode, sel));
}
这个解决方案使用了HTML5规范的一些新特性,并且在旧的/不兼容的浏览器(阅读: Internet Explorer)上使用它将需要polyfill。
Element.prototype.matches = (Element.prototype.matches || Element.prototype.mozMatchesSelector
|| Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector
|| Element.prototype.webkitMatchesSelector || Element.prototype.webkitMatchesSelector);
https://stackoverflow.com/questions/18663941
复制相似问题