猿问

在没有jQuery的情况下找到最接近的元素

我试图找到没有jquery的具有特定标签名称的最接近的元素。当我单击a时,<th>我想访问<tbody>该表的。有什么建议吗?我读过有关偏移量的信息,但并不太了解。我应该只使用:


假设已经设置了单击元素


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


墨色风雨
浏览 444回答 3
3回答

holdtom

晚会很少(很晚),但是。这应该做的伎俩:function closest(el, selector) {&nbsp; &nbsp; var matchesFn;&nbsp; &nbsp; // find vendor prefix&nbsp; &nbsp; ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {&nbsp; &nbsp; &nbsp; &nbsp; if (typeof document.body[fn] == 'function') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; matchesFn = fn;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; })&nbsp; &nbsp; var parent;&nbsp; &nbsp; // traverse parents&nbsp; &nbsp; while (el) {&nbsp; &nbsp; &nbsp; &nbsp; parent = el.parentElement;&nbsp; &nbsp; &nbsp; &nbsp; if (parent && parent[matchesFn](selector)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return parent;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; el = parent;&nbsp; &nbsp; }&nbsp; &nbsp; return null;}

慕容708150

在不使用jQuery的情况下,按标签名称获取最接近的元素的方法如下:function getClosest(el, tag) {&nbsp; // this is necessary since nodeName is always in upper case&nbsp; tag = tag.toUpperCase();&nbsp; do {&nbsp; &nbsp; if (el.nodeName === tag) {&nbsp; &nbsp; &nbsp; // tag name is found! let's return it. :)&nbsp; &nbsp; &nbsp; return el;&nbsp; &nbsp; }&nbsp; } while (el = el.parentNode);&nbsp; // not found :(&nbsp; return null;}getClosest(th, 'tbody');
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答