正如你在下面看到的,我清楚地重复了一遍。我知道这是不好的做法。

那么,如何将 if 和 else 语句中的 4 行重复代码重构为一行呢?

对更好的实践的一些指导将不胜感激。此外,您发现有助于学习此技术的任何 DRY 引用资料/教程。

$('.inner_wrap .details').click(function() {
    var index = $('.inner_wrap .details').index(this);

    $('.details').removeClass('here');
    $(this).addClass('here');
    $('.view').removeClass('active');
    $(this).find('.view').addClass('active');
    console.log(index);
    if(index > 2){
        index -= 3;
        **// This and its corresponding else statement is the topic of the question**
        $(this).closest('.outer_wrapper').prev('.outer_wrapper').find('.tabSlide').removeClass('tabShow');
        $(this).closest('.outer_wrapper').prev('.outer_wrapper').find('.tabSlide:eq(' + index + ')').addClass('tabShow');
    } else {
        $(this).closest('.outer_wrapper').prev('.outer_wrapper').find('.tabSlide').removeClass('tabShow');
        $(this).closest('.outer_wrapper').prev('.outer_wrapper').find('.tabSlide:eq(' + index + ')').addClass('tabShow');
    }

    return false;
});

最佳答案

if(index > 2){ index -= 3; }
**// This and its corresponding else statement is the topic of the question**
$(this).closest('.outer_wrapper').prev('.outer_wrapper')
       .find('.tabSlide').removeClass('tabShow')
       .eq(index).addClass('tabShow')

放弃 else,因为您正在执行该代码,而无需将其包含在语句中。您也可以继续在链上工作,因为您首先使用类 tabSlide 定位所有元素,然后根据其索引仅定位该类的特定实例。

关于javascript - jQuery 干货功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13495611/

10-10 13:47