<div class='red'>
<span class='orange'>
<div class='green'>
<div class="yellow">
<p>who is closer to me red or green??</p>
</div>
</div>
</span>
</div>
上面是我的html,jquery中的i want to compare green or red which one is closer to <p>
??,我试过
$(this).parents().hasClass("red");
但那对我不起作用..帮助我..
答案 0 :(得分:5)
单向:)
$('p').click(function () {
var cls = $(this).parents('div').filter(function () { //filter all div parents
return $(this).is('.green, .red'); //filter element who have class green or red
}).attr('class'); //get the attr of the first matched element
alert(cls);
});
<小时/> 获取元素检查控制台日志
<小时/> 评论后更新
$('p').click(function () {
var cls = $(this).parents('div').filter(function () { //filter all div parents
return $(this).is('.green, .red'); //filter element who have class green or red
}).attr('class'); //get the attr of the first matched element
alert(cls.match(/(green|red)\s?/i)[0] + ' is closer.');
});
答案 1 :(得分:3)
在此背景下尝试使用.parentsUntill()
,
var xCollection1 = $('p').parentsUntil('.red');
var xCollection2 = $('p').parentsUntil('.green');
if (xCollection1.length < xCollection2.length) {
alert('red is nearer');
} else {
alert('green is nearer');
}
答案 2 :(得分:3)
这是一个相对简单的解决方案:
var item = $(this).closest(".red, .green");
if (!item.length) {
console.log("no red or green parents");
} else if (item.hasClass("red")) {
console.log("red");
} else {
console.log("green");
}
工作演示:http://jsfiddle.net/jfriend00/Xcz98/
而且,如果你很好奇,这里有一个简单的javascript方法:
// pass starting node and space separated class list
// returns the class from the list it found first or "" if none were found
function findClosestParentClass(node, classes) {
var regex = new RegExp(" " + classes.replace(" ", " | ") + " ");
var cls, match;
node = node.parentNode;
do {
cls = " " + node.className + " ";
match = cls.match(regex);
if (match) {
return match[0].replace(/ /g, "");
}
node = node.parentNode;
} while (node && node !== document.documentElement);
return "";
}
答案 3 :(得分:2)
你可以试试这个:
var parents = $(this).parents('div').map(function() {
return $(this).attr('class');
}).get();
if(parents.indexOf("red") < parents.indexOf("green")) {
alert('red is closer to me');
}
else {
alert('green is closer to me');
}
答案 4 :(得分:1)
因此,parents()
数组中的索引越大,远离<p>
元素的DOM树中的索引越远。现在,这是遍历数组并查看每个类名的问题。
要查看哪个更靠近DOM,您需要比较要检查的每个元素的索引。
在这种情况下,类.red
的元素位于索引3,类.green
的元素位于索引1.这意味着绿色更接近。
$(document).ready(function() {
var indexOfRed;
var indexOfGreen;
$('p').click(function() {
$(this).parents().each(function(index, el) {
if ( $(el).hasClass('red') ) {
indexOfRed = index;
}
if ( $(el).hasClass('green') ) {
indexOfGreen = index;
}
});
if(indexOfRed < indexOfGreen) {
alert('red is closer to me');
} else {
alert('green is closer to me');
}
});
});