<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>
Run Code Online (Sandbox Code Playgroud)
上面是我的html,i want to compare green or red which one is closer to <p>在jquery中,我试过了
$(this).parents().hasClass("red");
Run Code Online (Sandbox Code Playgroud)
但那对我不起作用..帮帮我..
单程 :)
$('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);
});
Run Code Online (Sandbox Code Playgroud)
$('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.');
});
Run Code Online (Sandbox Code Playgroud)