【问题标题】:Why does jQuery not remove the class为什么jQuery不删除类
【发布时间】:2026-01-14 19:20:03
【问题描述】:

我正在运行一些 jQuery 来添加/删除当前类。它适用于兄弟姐妹,但不适用于兄弟姐妹的孩子。有人有什么好主意吗?

$('#rotator_buttons td').click(function(){
    if($(this).hasClass('current')) {
        $(this).removeClass('current');
    }
    else {
        $(this).addClass('current').siblings().removeClass('current');
        $(this).siblings().children('a').removeClass('current');
        $(this).children('a').addClass('current');

    }
   return false;
});

HTML

<table id="rotator_buttons">
<tbody>
<tr>
  <td id="pause-play"><a href="#"><!-- --></a></td>
  <td><a href="#" id="1" target="_self" onclick="javascript:increment_slideshow(0)">Button 1</a></td>
  <td><a href="#" id="2" target="_self" onclick="javascript:increment_slideshow(0)">Button 2</a></td>
  <td><a href="#" id="3" target="_self" onclick="javascript:increment_slideshow(0)">Button 3</a></td>
  <td><a href="#" id="4" target="_self" onclick="javascript:increment_slideshow(0)">Button 4</a></td>
</tr>

【问题讨论】:

  • 它们实际上是孩子,还是嵌套更深?当我们看不到 DOM 时,几乎不可能回答 DOM 选择问题。
  • 根据 current 类的使用位置,您可能只想使用 $(this).parent().find('.current').removeClass('current')

标签: jquery html highlight


【解决方案1】:
$('#rotator_buttons td').click(function(){
    if($(this).hasClass('current')) {
        $(this).removeClass('current');
    }
    else {
        $(this).children('a').addClass('current');
        $(this).siblings().each(function(){
            $(this).removeClass('current');
            $(this).children('a').removeClass('current');
        });
    }
    return false;
});

【讨论】: