找其他复选框

时间:2011-11-07 11:16:28

标签: javascript jquery

请参阅js代码中的评论。

我有两个复选框

<input type="checkbox" name="first" id="first" />
<input type="checkbox" name="second" id="second" />

这是我的javascript

$(function() {
  $('input[type=checkbox]').click(function() {
      /* 
       HERE i want to manipulate the checkbox which is not clicked
       NOTICE: they are only two checkboxes in page

       I know that I can do something like this
       if($(this).attr('id') == "first) {
           do something
       } else {
          etc...
       }
       But I think that way is against DNRY
       Can you recommend me some more elegenat solution ?

       /*
    }
    });
});

3 个答案:

答案 0 :(得分:2)

你可以这样做:

$('input[type=checkbox]').click(function() {
  /*
   HERE i want to manipulate the checkbox which is not clicked
   NOTICE: they are only two checkboxes in page

   I know that I can do something like this
   if($(this).attr('id') == "first) {
       do something
   } else {
      etc...
   }
   But I think that way is against DNRY
   Can you recommend me some more elegenat solution ?

   */
  //you can get the other checkbox by filtering out the element you clicked
  //in this case i hide it
  $('input:checkbox').not(this).hide();

});

答案 1 :(得分:2)

您只想使用.not过滤掉当前点击的项目(this

$(function() {
    var checkboxes = $('input[type=checkbox]');
    checkboxes.click(function() {
        var notclicked = checkboxes.not(this);
    }
});

http://jsfiddle.net/infernalbadger/amz7f/

答案 2 :(得分:1)

您可以使用.not()功能排除当前/单击的复选框。例如

$(function() {
    var $checkboxes = $('input[type=checkbox]')

    $checkboxes.click(function() {
        var $other = $checkboxes.not(this);
        ...
    });
});