1

我要做的就是根据我编写的计数脚本的结果使 div 淡出。一切正常,但唯一不能正常工作的是当值返回到名为计数器的 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>
4

3 回答 3

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);
      }
 });
于 2013-03-20T16:15:32.303 回答
0

将您的if语句放在点击处理程序中并使用count而不是$('#counter').text().
jsFiddle

于 2013-03-20T16:14:40.187 回答
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);
    }

});

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

于 2013-03-20T16:21:36.580 回答