jQuery:优化代码(学习案例)



我不得不承认,在我自己尝试和学习的所有时间里,我看到许多jQuery脚本,纯粹凭直觉想出了这个解决方案。

由于我没有任何人亲自问这类问题,这就是我来这里寻求帮助和指导的原因。

--

受到Wufoo计划表单的启发,在填写表单时突出显示您需要关注的行,我创建了这个脚本(我不是jQuery或JavaScript大师,我仍在学习和练习):

//Improve usability by highlighting the row the user needs to focus on:
$(function() {
        //When input element has focus
        $('input').focus(function(){
            //Add the class to its corresponding row
            $(this).parent().parent('.row').addClass('focus'),
                //And when it loses focus
                $('input').blur(function(){
                    //Remove the class
                    $(this).parent().parent('.row').removeClass('focus');
                });
        });
});

所以我想知道这个脚本是否有办法写得更好或以任何方式优化/缩短。如果没有,我写它的方式是好的,没关系,我想学习的只是在可能的情况下优化代码的方法,仅此而已。

如果你想看看,我在Codepen中创建了一个演示

提前谢谢。

你可以这样做:

//Improve usability by highlighting the row the user needs to focus on:
$(function() {
        $('input').focus(function(){
            $(this).closest('.row').addClass('focus'); // Change here                    
        }).blur(function(){ // Change here
           $(this).closest('.row').removeClass('focus'); // Change here
        });
});

甚至更短!

$(function(){
    $("input").on("focus blur", function(){
        $(this).closest(".row").toggleClass("focus");
    });
});

你做错了一件事!!每次对焦时,您都会在每个输入上绑定一个新的模糊!

代码看起来不错。我所做的唯一更改是使用 closest() 而不是链接parent()调用,就像您更改周围的 DOM 一样,您需要更改 jQuery 代码。此外,我会将blur()处理程序移到focus()处理程序之外。试试这个:

$(function() {
    $('input')
        .focus(function() {
            $(this).closest('.row').addClass('focus');
        })
        .blur(function() {
            $(this).closest('.row').removeClass('focus');
        });
});

我会尝试将我的偶数处理程序和事件绑定分开。这对于实际将事件绑定到所有当前和未来.row元素的.on()来说很方便,这与仅绑定发生绑定时页面上的行上的.focus()不同。

这样,您也不需要将代码包装到$(function(){});中。您可以将事件绑定放在包含的.js文件中,而不是将 jQuery 与标记混合使用。

此外,请使用.closest()而不是.parent().parent()因为如果您选择稍微更改结构,它不会中断。前提是您的.row仍然存在。

var onRowFocus = function(){
    $('.row').removeClass('focus');
    $(this).closest('.row').addClass('focus');
};
$('.row').on('focus', 'input', onRowFocus);

此外,您根本不需要绑定 .blur 事件。只需从所有行中删除 focus 类,然后再将其添加到焦点上的行。更少的事件处理程序,更少的代码,更易于维护。

最新更新