2012-01-17 56 views
0

好了,所以我有這個jQuery的功能,抓住複選框的值,並使用作爲標識,以顯示或隱藏ULjQuery的只有1項inArray

的問題是,我不能設法如果添加只有1複選框選擇添加X.

這裏是代碼,我曾嘗試

$('#filter li input:checkbox').change(
    function(){ 
     var show = $('input:checkbox:checked').map(function(){ 
      return $(this).val(); 
     }); 
     if (show.length > 0) 
     { 
       $('#list li').each(
       function(){ 
        /*if ($.inArray($(this).attr('class'),show) <= 1) 
        { 
         console.log($(this)); 
        } 
        else */if ($.inArray($(this).attr('class'),show) > -1) 
        {       
         $(this).show(); 
        } 
        else 
        { 
         $(this).hide(); 
        } 
       }); 
     } 
     else { 
      $('#list li').show(); 
     } 
    }); 

我真的不明白這是如何工作:if ($.inArray($(this).attr('class'),show) > -1)因爲我已經試過if ($.inArray($(this).attr('class'),show) = 1)並沒有什麼

回答

3

你的if子句中分配一個值:

if ($.inArray($(this).attr('class'),show) = 1) 

要打破它,這是什麼東西實際上是在說,相當於

$.inArray($(this).attr('class'),show) = 1; 
if ($.inArray($(this).attr('class'),show)) 
{ 
    ... 

您應該使用==比較運算符

if ($.inArray($(this).attr('class'),show) == 1) 

或者,更正確地避免類型coersion,使用===

if ($.inArray($(this).attr('class'),show) === 1) 

這將避免1"1"之間的比較返回true

+0

對不起,我已刪除了發佈前...這是不是這樣的......我需要修復'if'內'$('#list li')。each(...' – Alex 2012-01-17 12:14:27

+0

Errrr,好吧,同樣適用。改用'==='。 'if($ .inArray($(this).attr('class'),show)=== 1)' – 2012-01-17 12:15:39

+0

由於某些原因,它不起作用。我已經嘗試了'如果($ .inArray($(this).attr('class'),show)== 1)'還有'=== 1',並且我添加的警報不會彈出 – Alex 2012-01-17 12:23:19