2011-11-07 69 views
2

請在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 ? 

     /* 
    } 
    }); 
}); 

回答

2

你只是想用.not篩選出當前點擊項目(this

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

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

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

可以使用.not()功能,以排除電流/點擊複選框。例如。

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

    $checkboxes.click(function() { 
     var $other = $checkboxes.not(this); 
     ... 
    }); 
}); 
相關問題