我试图找到没有jquery的具有特定标记名称的最接近的元素。当我点击时,<th>我想访问<tbody>该表的。有什么建议吗?我读过有关偏移量的信息,但并不太了解。我应该只使用:
假设已经设置了单击元素
th.offsetParent.getElementsByTagName('tbody')[0]
我试图找到没有jquery的具有特定标记名称的最接近的元素。当我点击时,<th>我想访问<tbody>该表的。有什么建议吗?我读过有关偏移量的信息,但并不太了解。我应该只使用:
假设已经设置了单击元素
th.offsetParent.getElementsByTagName('tbody')[0]
el.closest('tbody')对于非IE浏览器。请参阅下面的详细说明的答案+ polyfill。
Answers:
晚会很少(很晚),但是。这应该做的伎俩:
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;
}
eljQuery.closest()和Element.closest()的元素。for( var parent = el ; parent !== null && !parent[matchesFn](selector) ; parent = el.parentElement ){ el = parent; } return parent;
parent全局范围内定义(!)
el.parentNode否则在IE中遍历SVG时可能会中断。
很简单的:
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
在不使用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');
有一个标准化的函数可以执行此操作:Element.closest。除IE11之外,大多数浏览器都支持它(caniuse.com进行了详细介绍)。的MDN文档还包括如果你有目标旧版浏览器的一个填充工具。
要找到tbody给定的最接近的父级,th您可以执行以下操作:
th.closest('tbody');
如果您想自己编写函数,这是我想到的:
function findClosestParent (startElement, fn) {
var parent = startElement.parentElement;
if (!parent) return undefined;
return fn(parent) ? parent : findClosestParent(parent, fn);
}
要通过标签名称查找最接近的父级,可以这样使用:
findClosestParent(x, element => return element.tagName === "SECTION");
function closest(el, sel) {
if (el != null)
return el.matches(sel) ? el
: (el.querySelector(sel)
|| closest(el.parentNode, sel));
}
此解决方案使用了HTML 5规范的一些最新功能,并且在较旧/不兼容的浏览器(请参阅:Internet Explorer)上使用此功能将需要使用polyfill。
Element.prototype.matches = (Element.prototype.matches || Element.prototype.mozMatchesSelector
|| Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector
|| Element.prototype.webkitMatchesSelector || Element.prototype.webkitMatchesSelector);
扩展@SalmanPK答案
它将允许使用节点作为选择器,在处理鼠标悬停等事件时很有用。
function closest(el, selector) {
if (typeof selector === 'string') {
matches = el.webkitMatchesSelector ? 'webkitMatchesSelector' : (el.msMatchesSelector ? 'msMatchesSelector' : 'matches');
while (el.parentElement) {
if (el[matches](selector)) {
return el
};
el = el.parentElement;
}
} else {
while (el.parentElement) {
if (el === selector) {
return el
};
el = el.parentElement;
}
}
return null;
}
为了找到特定的祖先,我们可以使用:
Element.closest();
此函数将CSS选择器字符串作为参数。然后,它返回当前元素(或元素本身)的最接近的祖先,该祖先与参数中传递的CSS选择器相匹配。如果没有祖先,它将返回null。
const child = document.querySelector('.child');
// select the child
console.dir(child.closest('.parent').className);
// check if there is any ancestor called parent
<div class="parent">
<div></div>
<div>
<div></div>
<div class="child"></div>
</div>
</div>
在包含类,ID,数据属性或标签的树上获取最接近的DOM元素。包括元素本身。支持回IE6。
var getClosest = function (elem, selector) {
var firstChar = selector.charAt(0);
// Get closest match
for ( ; elem && elem !== document; elem = elem.parentNode ) {
// If selector is a class
if ( firstChar === '.' ) {
if ( elem.classList.contains( selector.substr(1) ) ) {
return elem;
}
}
// If selector is an ID
if ( firstChar === '#' ) {
if ( elem.id === selector.substr(1) ) {
return elem;
}
}
// If selector is a data attribute
if ( firstChar === '[' ) {
if ( elem.hasAttribute( selector.substr(1, selector.length - 2) ) ) {
return elem;
}
}
// If selector is a tag
if ( elem.tagName.toLowerCase() === selector ) {
return elem;
}
}
return false;
};
var elem = document.querySelector('#some-element');
var closest = getClosest(elem, '.some-class');
var closestLink = getClosest(elem, 'a');
var closestExcludingElement = getClosest(elem.parentNode, '.some-class');
firstChar为所有IF条件使用开关?
for循环?
查找最近的Elements子节点。
closest:function(el, selector,userMatchFn) {
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;
});
function findInChilds(el){
if(!el) return false;
if(el && el[matchesFn] && el[matchesFn](selector)
&& userMatchFn(el) ) return [el];
var resultAsArr=[];
if(el.childNodes && el.childNodes.length){
for(var i=0;i< el.childNodes.length;i++)
{
var child=el.childNodes[i];
var resultForChild=findInChilds(child);
if(resultForChild instanceof Array){
for(var j=0;j<resultForChild.length;j++)
{
resultAsArr.push(resultForChild[j]);
}
}
}
}
return resultAsArr.length?resultAsArr: false;
}
var parent;
if(!userMatchFn || arguments.length==2) userMatchFn=function(){return true;}
while (el) {
parent = el.parentElement;
result=findInChilds(parent);
if (result) return result;
el = parent;
}
return null;
}
这里。
function findNearest(el, tag) {
while( el && el.tagName && el.tagName !== tag.toUpperCase()) {
el = el.nextSibling;
} return el;
}
只在树下找到兄弟姐妹。使用previousSibling进行其他选择,或使用变量遍历两种方法并返回最先找到的那个。您已基本了解,但是如果您要遍历parentNodes或子级不匹配的子级,则可以使用jQuery。在这一点上,它很值得。
我认为最容易用jquery捕获的代码最接近:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(".add").on("click", function () {
var v = $(this).closest(".division").find("input[name='roll']").val();
alert(v);
});
});
</script>
<?php
for ($i = 1; $i <= 5; $i++) {
echo'<div class = "division">'
. '<form method="POST" action="">'
. '<p><input type="number" name="roll" placeholder="Enter Roll"></p>'
. '<p><input type="button" class="add" name = "submit" value = "Click"></p>'
. '</form></div>';
}
?>
非常感谢。