哪个类更接近jquery中的元素A或B.

时间:2014-05-12 06:19:42

标签: jquery html class

<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");

但那对我不起作用..帮助我..

5 个答案:

答案 0 :(得分:5)

Fiddle Demo

单向:)

$('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);
});

<小时/> 获取元素检查控制台日志

Fiddle Demo

<小时/> 评论后更新

Updated Fiddle Demo

$('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');
}

DEMO

答案 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 "";
}

工作演示:http://jsfiddle.net/jfriend00/f3dHm/

答案 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');   
}

Working Example

答案 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');   
        }
    });
});

http://jsfiddle.net/JvNmT/