2015-12-21 110 views
1

此功能(使用option:selected)更改了<div class="item">0</div>的CSS和HTML以模拟一种进度条应用程序。问题是它超过了100%。所以if陈述是不正确的或这里是错误的?任何线索?在if/else语句中,e.preventDefault()未对条件执行100%

$(function(){ 
    $('#selectChoice').change(function() { 
     $('option:selected', this).each(function() { 
      var id = $('#selectChoice option:selected').attr('id'); 
      $('#' + id + 'Item').css("color", "#f00").css("font-weight", "bold"); 
     }); 
    }); 

    $('#plus25').on('click', function() { 
     var id = $('#selectChoice option:selected').attr('id'); 
     $('#' + id + 'Item').html(function(i, value) { 
      var newWidth = parseInt(value * 1 + 25); 
      var e = window.event; 
      $('#' + id + 'Item').css('width', newWidth + '%'); 
      if (value <= 75){ 
       return newWidth; 
      } else { 
       e.PreventDefault();} 
      }); 
     }); 
    }); 

以下条件也做奇怪的事情在0

if (value >= 25) { 
    return newWidth; 
} 

完整版可here

+0

以下IE错误修正是由于@amitthk: 否则{safePreventDefault(E);} }); });对于IE错误 evt = evt || window.event; if(evt){evg.returnValue = false; } if((evt)&&(evt.preventDefault)) {evt.preventDefault(); } }; –

+1

让'e是未定义的'。使用'function(e)'。删除'var e = window.event;' –

+0

感谢@Parth Trivedi。也许'var e = evt || window.event;'需要在其他地方定义? –

回答

3

您应该使用传入的event对象到click处理程序,而不是全球window.event。另外,该方法是小写的preventDefault()。尝试:

$('#plus25').on('click', function(e) { // Note the 'e' parameter here 
    var id = $('#selectChoice option:selected').attr('id'); 
    $('#' + id + 'Item').html(function(i, value) { 
     var newWidth = parseInt(value * 1 + 25); 
     $('#' + id + 'Item').css('width', newWidth + '%'); 
     if (value <= 75) { 
      return newWidth; 
     } else { 
      e.preventDefault(); 
     } 
    }); 
}); 
+0

谢谢@ Rory McCrossan,但它仍然超过100% –

+0

使用'newWidth <100'而不是'value <75'。 –

+0

我想'if' /'else'需要更多的条件..究竟是什么让我难以想象。也许'else if' –