0

在按钮 1 的单击事件中,如何仅从本节中删除“选定”类。不应删除 Button 2 的类,对于 Button 2 也是如此,如果我单击按钮 2,如果选择的类存在,则不应删除 Button 1 的类。我知道$('.small-button-1, .small-button-2').removeClass('selected');删除一切。

<div class="block">
    <div id="abcd" class="lg_button">Button 1</div>
    <div>
        <div class="small-button-1 selected">1</div>
        <div class="small-button-2 selected">2</div>
    </div>
</div> 

<div class="block">
    <div id="dcba" class="lg_button">Button 2</div>
    <div>
        <div class="small-button-1 selected">1</div>
        <div class="small-button-2 selected">2</div>
    </div>
</div> 
4

2 回答 2

1

我已经这样做了,但必须重命名一些 html 标签才能让它在这里工作是我的例子 http://jsfiddle.net/fKwGR/

jquery部分:

$(document).ready(function() {
$('div.lg_button1').click(function(){
        $('div.small-button-1.selected').attr('class','small-button-1');
        $('div.small-button-2.selected').attr('class','small-button-2');
        $('div.small-button-3').attr('class','small-button-3 selected');
        $('div.small-button-4').attr('class','small-button-4 selected');
        });
$('div.lg_button2').click(function(){
        $('div.small-button-1').attr('class','small-button-1 selected');
        $('div.small-button-2').attr('class','small-button-2 selected');
        $('div.small-button-3.selected').attr('class','small-button-3');
        $('div.small-button-4.selected').attr('class','small-button-4');
        });
});​

HTML部分:

<div class="block">
  <div id="abcd" class="lg_button1">Button 1</div>
  <div id='button1'>
      <div class="small-button-1 selected">1</div>
      <div class="small-button-2 selected">2</div>
  </div>

<div class="block">
  <div id="dcba" class="lg_button2">Button 2</div>
  <div id='button2'>
      <div class="small-button-3 selected">1</div>
      <div class="small-button-4 selected">2</div>
  </div>

​</p>

于 2012-07-23T12:34:02.670 回答
0

我相信您需要掌握父元素,然后将其用作选择器的上下文。像这样的东西http://jsfiddle.net/VY5Md/应该实现你所要求的我认为

  $(function(){
       $('.lg_button').click(function(){
           var $p = $(this).parents('.block');
           $('.selected', $p).removeClass('selected'); 
       }); 
  });​

此代码获取单击的按钮,找到具有类“块”的父级,然后在该“块”的上下文中从具有“选定”类的任何内容中删除“选定”类

于 2012-07-23T12:19:19.640 回答