【问题标题】:Add class to even elements when even element is clicked and add class to odd elements when odd element is clicked单击偶数元素时将类添加到偶数元素,单击奇数元素时将类添加到奇数元素
【发布时间】:2014-06-28 10:59:06
【问题描述】:

我试图在单击偶数元素时向偶数元素添加类,并在单击奇数元素时向奇数元素添加类。

我尝试过使用 :nth-child(even) :nth-child(odd) 但我似乎不知道如何判断单击的元素是偶数还是奇数。

考虑一下这个基本的 HTML

<ul id="list">
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li>four</li>
    <li>five</li>
    <li>six</li>
    <li>seven</li>
    <li>eight</li>
</ul>

如果您单击“二”,则应突出显示元素二、四、大小和八。如果单击一,则应突出显示元素一、三、五和七。 (当我说突出显示时,我可能只是添加一个类:

.red {
    background:red;
}

【问题讨论】:

  • red 是一个错误的类名。在某些时候,您可能想要更改突出显示的颜色,最终得到类似.red { background: blue; }
  • 奇数和偶数是指列表项的实际文本值吗?或者只是他们在列表中的索引?因此,如果第一项是“二”,那仍然算奇数吗? :nth-child(even) :nth-child(odd) 有什么问题?

标签: javascript jquery html css


【解决方案1】:

这是一种方法:

Example Here

$("#list > li").on("click",function(){
    $('.red').removeClass('red');
    if($(this).index() % 2 == 0) {
       $('#list > li:even').addClass('red');
    } else {
       $('#list > li:odd').addClass('red');
    }
});

使用$(this).index() % 2 == 0 判断点击的元素是偶数还是奇数。然后分别使用:even/:odd添加类。

【讨论】:

  • 谢谢。这适用于您的示例,但不适用于我的网站。有什么想法吗?
  • @Greg4Hughes 可能是您应该将此代码包装在 doc ready 处理程序中并在此脚本之前加载 jQuery。
  • 我的错。我忘了包括 jQuery。它可以按我现在的需要工作。再次感谢!
  • 我还有一个问题。我应该在这里提问还是提出一个新问题?
  • 最好在其他地方问,如果这与它有关,你可以在这里问。:)
【解决方案2】:

只需这样做:

$('#list li').click(function(){
    $('#list li').removeClass('red'); // remove the red class first
    ($(this).index() % 2 === 0) ? $('#list li:even').addClass('red') : $('#list li:odd').addClass('red');
});

【讨论】:

    【解决方案3】:

    没有 jQuery。

    (function() {
      var nodes = document.querySelectorAll("#list li");
      for (var i = 0; i < nodes.length; i++)
        setup(nodes[i],i); 
    
      function setup(node, index) {
        node.addEventListener("click", function() {
            for (var j = 0; j < nodes.length; j++) {
                nodes[j].classList.remove("red");
                if (index % 2 === 0 && j % 2 === 0 ||index % 2 === 1 && j % 2 === 1) {
                    nodes[j].classList.add("red");
                }
            }
        });
      }
    }());
    

    【讨论】:

      猜你喜欢
      • 2020-10-02
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 2015-11-19
      • 2016-02-21
      • 1970-01-01
      • 2022-12-14
      相关资源
      最近更新 更多