如何检查元素是否不是所选元素

时间:2013-09-16 12:26:27

标签: jquery html

我正在寻找一个jQuery方法,如何检查特定元素是否不是其他元素之一。 这是一个普遍的问题,因为我以前做的方式如下。

假设我有一个带有5个按钮的菜单栏,如果点击按钮,我想要发射一些东西

$('#button1').click(function() {
   $(this).css('color','blue');
   $('#button2').css('color','red');
   $('#button3').css('color','red');
   $('#button4').css('color','red'); 
}

$('#button2').click(function() {
   $(this).css('color','blue');
   $('#button1'.css('color','red');
   $('#button3').css('color','red');
   $('#button4').css('color','red'); 
} // and so on for #button3, 4 ...

这当然有效。但它似乎为一些按钮编写了很多代码。问题是,我怎么能问这样的事情:

$(this).click(function() {
  $(this).css('color','blue');
  $(all others).css('color','red'); }

我必须使用Arrays,还是有jQuery解决方案?提前谢谢!

4 个答案:

答案 0 :(得分:1)

您可以使用 attributes-starts-with selector

 $(this).click(function() {
    $('[id^="button"]').css('color','red');   
    $(this).css('color','blue');
      }

答案 1 :(得分:1)

而不是使用id为所有相关按钮添加一个公共类,然后

var $btns = $('.mybuttons').click(function(){
    $(this).css('color','blue');
    $btns.not(this).css('color','red'); 
})

演示:Fiddle

更新

$('body').on('click', '.sublink', function () {
    $(this).css('color', '#393fad');
    $('.sublink').not(this).css('color', '#8b8b8b');
})

演示:Fiddle

答案 2 :(得分:0)

如果他们都在这样的div中,你可以使用.siblings()

<强>的jQuery

$(document).ready(function () {
    $('div button').on('click', function () {
        $(this).css('color', 'blue').siblings().css('color', 'red');
    });
});

<强> HTML

<div>
<button id="button1">test1</button>
<button id="button2">test2</button>
<button id="button3">test3</button>
<button id="button4">test4</button>
</div>

答案 3 :(得分:0)

首先将所有按钮的颜色设置为红色。 参加一个共同的课程

 $('.all_button').click(function() {
    $('.all_button').css('color','red');
    $(this).css('color','blue');
)};

我认为这应该有用。