2017-03-13 38 views
0

我在if語句中玩耍,但遇到了一些麻煩。我想將隨機數傳遞給一個變量,然後根據點擊事件做出某些事情。如何在jquery if語句中使用隨機數計數器

下面是我周圍玩,但它不工作:

$(document).ready(function() { 
    var $r; 

    $('.cell').click(function() { 
    $r = Math.floor(Math.random() * 5); 
    if $($r == 3) { 
     $(this).addClass('img'); 
    } else { 
     $(this).css("background-color", "‎#708090").slideUp(150).slideDown(150); 

    } 

    }); 
}); 
+0

'如果$($ R == 3)'應該是'如果($ R == 3)'。爲什麼太多'$'? –

+0

爲了查看錯誤,請打開瀏覽器附帶的開發者控制檯(通常按F12)。 – 4castle

+0

這是一個錯誤文字? – guradio

回答

2

只是一對夫婦在這裏和那裏錯別字。我還添加.removeClass的條件,所以你可以刪除.IMG造型如果RAN num是不是3:

var r = Math.floor(Math.random() * 5); 
if (r == 3) { 
    $(this).addClass('img'); 
} else { 
    $(this).removeClass('img'); 
    $(this).css("background-color", "#708090").slideUp(150).slideDown(150); 
} 

https://jsfiddle.net/04m0fgxj/6/

+0

這也適用!非常感謝。 – geniusmind

1
Try this code 

var r; 
    $(".cell").click(function(){ 
     r = Math.floor(Math.random() * 5); 
      if (r == 3) { 
        $(this).addClass('img'); 
      } else { 
        $(this).css("background-color","#708090").slideUp(150).slideDown(150); 

      } 
    }); 

There is no necessary of declaring a variable in $ 
+0

這也適用!非常感謝。 – geniusmind

2

夫婦的事情是錯誤的了Syntex。額外'$'和'})'。

$('.cell').click(function() { 
 
    $r = Math.floor(Math.random() * 5); 
 
    //$r=3; // uncomment this for check addClass img 
 
    if ($r == 3) { 
 
    $(this).addClass('img'); 
 
    } else { 
 
    $(this).css("background-color", "#708090").slideUp(150).slideDown(150); 
 

 
    } 
 

 
});
.cell { 
 
    width: 100px; 
 
    margin: auto; 
 
    border: 3px solid; 
 
    height: 100px; 
 
} 
 
.img{ 
 
    background-color: red; 
 
}

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class='cell'> 
 

 
</div>

+0

這也適用!非常感謝。 – geniusmind