根据jquery中的数学结果使div淡出

时间:2013-03-20 16:12:10

标签: jquery html

我想要做的就是根据我编写的计数脚本的结果使div淡出。一切正常,但唯一不能正常工作的是当值返回到一个名为counter的div时,div淡出。这是一个jsfiddle - http://jsfiddle.net/andyjh07/fBqRK/,javascript代码如下:

jquery -

$('#trigger').on('click', function(){

   // Count all of the checked boxes and then output the result
   var count = $("[type='checkbox']:checked").length;
   var fadespeed = 500;
   $('#counter').text(count).fadeIn(fadespeed);

   // Now, depending on the results, display some stuff
    var message = $('#message');
    if(count >= 8){
        message.fadeIn(fadespeed).text('You have done really well');
    } else if (count >= 4) {
        message.fadeIn(fadespeed).text('You are sort of okay');
    } else {
        message.fadeIn(fadespeed).text('You are terrible, sorry.')   
    }
});

if($('#counter').text() == 2){
    $('#buttons').fadeOut(500);
}

HTML -

<input type="checkbox" value="Yes"/>
<input type="checkbox" value="Yes"/>
<input type="checkbox" value="Yes"/>
<input type="checkbox" value="Yes"/>
<input type="checkbox" value="Yes"/>
<input type="checkbox" value="Yes"/>
<input type="checkbox" value="Yes"/>
<input type="checkbox" value="Yes"/>
<input type="checkbox" value="Yes"/>
<input type="checkbox" value="Yes"/>


<div id="trigger">Click to count 'em</div>
<div id="counter"></div>
<div id="message"></div>
<div id="buttons">Buttons</div>

3 个答案:

答案 0 :(得分:1)

目前,您的if statement将在页面加载时运行,当JS文件打开并被执行时。您需要将if块移动到click事件中,即:

 $('#trigger').on('click', function(){

      // Count all of the checked boxes and then output the result
      var count = $("[type='checkbox']:checked").length;
      var fadespeed = 500;
      $('#counter').text(count).fadeIn(fadespeed);

      // Now, depending on the results, display some stuff
       var message = $('#message');
       if(count >= 8){
         message.fadeIn(fadespeed).text('You have done really well');
     } else if (count >= 4) {
         message.fadeIn(fadespeed).text('You are sort of okay');
     } else {
         message.fadeIn(fadespeed).text('You are terrible, sorry.')   
     }

      if($('#counter').text() == 2){
          $('#buttons').fadeOut(500);
      }
 });

答案 1 :(得分:0)

将您的if语句放入点击处理程序中,然后使用count代替$('#counter').text()
jsFiddle

答案 2 :(得分:0)

下面:

$('#trigger').on('click', function(){

   // Count all of the checked boxes and then output the result
   var count = $("[type='checkbox']:checked").length;
   var fadespeed = 500;
   $('#counter').text(count).fadeIn(fadespeed);

   // Now, depending on the results, display some stuff
    var message = $('#message');
    if(count >= 8){
        message.fadeIn(fadespeed).text('You have done really well');
    } else if (count >= 4) {
        message.fadeIn(fadespeed).text('You are sort of okay');
    } else {
        message.fadeIn(fadespeed).text('You are terrible, sorry.')   
    }

    if(count == 2){
        $('#buttons').fadeOut(500);
    }

});

在小提琴中尝试过......就像一个魅力......