这个函数(使用option:selected)改变了0的CSS和HTML来模拟一种进度条应用。 问题是它超过了 100%。那么返回“newWidth”时if语句不正确,还是其他什么地方不对?任何线索将不胜感激?
$(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();}
});
});
});
完整版可以看here
最佳答案
$('#plus25').on('click', function(e) {
var id = $('#selectChoice option:selected').attr('id'),
$target = $('#'+ id +'Item');
$target.html(function(i, value) {
var currentWidth = parseInt(value, 10),
newWidth = currentWidth + 25;
//check if the operation is valid first
if (newWidth <= 100) {
$target.css('width', newWidth +'%');
} else {
//update would have pushed it beyond 100.
//keep the original value
//don't change the css
newWidth = currentWidth;
}
return newWidth;
});
});
关于jquery - e.preventDefault() 不能 100% 满足 if/else 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34571940/