jquery - e.preventDefault() 不能 100% 满足 if/else 条件

标签 jquery css

这个函数(使用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/

相关文章:

javascript - 如何将 'cut' DOM元素显示在其他地方?

asp.net - 将复杂的 JSON 数据 jQuery 传递给 Action

javascript - 将列表转换为字典

javascript - 如何获取:contains() Selector using an Array with multiple matches in a DIV?的总实例

css - 在屏幕调整大小时自动调整图像大小

html - body 不低于 Bootstrap 导航

javascript - 如何使用 bootstrap/jquery 折叠/展开列表

javascript - 滚动到页面顶部时如何隐藏按钮?

javascript - 强制鼠标滚轮滚动到最后一部分

javascript - 如何创建固定 float 加号按钮?