【问题标题】:which class is closer to an element A or B in jquery哪个类更接近 jquery 中的元素 A 或 B
【发布时间】:2014-05-12 06:19:41
【问题描述】:
<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 &lt;p&gt;??,我试过了

  $(this).parents().hasClass("red");

但这对我不起作用..帮帮我..

【问题讨论】:

  • 你想只知道父 div 类名还是想比较绿色或红色哪个更接近?
  • 想要比较绿色或红色哪个更接近

标签: jquery html class


【解决方案1】:

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

【讨论】:

  • 啊,你比我强,这样更好。
  • 如果第一个带有绿色或红色的元素上面有其他类怎么办?
  • @jfriend00 他需要第一个匹配元素。
  • 他问哪个更接近红色或绿色。如果具有这些类之一的最接近的元素具有许多其他类怎么办。然后,您的算法将具有包含所有类的整个类名,而不仅仅是"red""green"。 TH OP 没有要求元素。他们问哪种颜色更接近。这就是我的观点。您的答案需要更多代码来检查生成的类名,以查看其中包含哪个类,从而知道哪个更接近。
  • @jfriend00 明白了,先生,抱歉 :) 已更新。]
【解决方案2】:

尝试在这种情况下使用.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

【讨论】:

  • @chriz 是的,显然.. :)
  • 如果红色和绿色都不存在??
  • @chriz 然后我们还要检查另一个条件,即xCollection1.length == 0 &amp;&amp; xCollection2.length == 0
【解决方案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/

【讨论】:

  • @chriz - 添加了对没有红色或绿色父母的情况的处理
  • @chriz - 通过使用.closest() 而不是.parents() 进一步简化了一点。
  • @chriz - 添加了一种普通的 JavaScript 方式。
【解决方案4】:

你可以试试这个:

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

【讨论】:

    【解决方案5】:

    因此,parents() 数组中的索引越大,它在 DOM 树中离您的&lt;p&gt; 元素越远。现在是遍历数组,查看每个类名的问题。

    要查看 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/

    【讨论】:

    • 当您不使用 jQuery 提供的所有抽象时,有时会更清楚发生了什么。
    猜你喜欢
    • 2011-08-19
    • 2011-11-07
    • 1970-01-01
    • 2014-08-12
    • 2023-03-15
    • 2019-07-29
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多