有什么办法可以使此文件变干?

时间:2020-05-09 21:24:39

标签: javascript jquery arraylist

看一下我的文件,目前困扰我的一件事是重复的部分和面板。我一定看不到大图,所以谁能告诉我一种更好的,更干燥的编码方法?

$(function() {

let pent = {
    init : function () {
        this.cacheDom();
        this.bindEvents();
    },
    cacheDom: function () {
        this.$el = $('#naver');
        this.$button = this.$el.find('#xCancel');
        this.$set = this.$el.find(".setting");
        this.$section = [
            this.$sectionA = this.$el.find('#set1'),
            this.$sectionB = this.$el.find('#set2'),
            this.$sectionC = this.$el.find('#set3'),
            this.$sectionD = this.$el.find('#set4')                
        ];            
        this.$panelA = this.$el.find('#settbox1');
        this.$panelB = this.$el.find('#settbox2');
        this.$panelC = this.$el.find('#settbox3');
        this.$panelD = this.$el.find('#settbox4');

    },
     bindEvents: function () {
        this.$button.on('click', this.hidePanel.bind(this));             
        this.$sectionA.on('click', this.showPanelA.bind(this));
        this.$sectionB.on('click', this.showPanelB.bind(this));
        this.$sectionC.on('click', this.showPanelC.bind(this));
        this.$sectionD.on('click', this.showPanelD.bind(this));
     },
     showPanelA: function () {
        this.$button.show();
        this.$panelA.slideDown(100);            
     },
     showPanelB: function () {
        this.$button.show();
        this.$panelB.slideDown(100);            
     },
     showPanelC: function () {
        this.$button.show();
        this.$panelC.slideDown(100);            
     },
     showPanelD: function () {
        this.$button.show();
        this.$panelD.slideDown(100);            
     },
     hidePanel : function () {
        this.$set.slideUp(100);
        this.$button.hide();
     },
};

pent.init();

});

1 个答案:

答案 0 :(得分:0)

更好的代码是:

$('#xCancel').on('click', function() {
  $('.setting').slideUp(100);
  $(this).hide();
});

$('.set1').on('click', function() {
  $('#xCancel').show();
  $('.settbox').slideDown(100);
});

只需遵循DRY principle,并使事情变得简单。我的意思是,如果您需要对更多元素执行相同的操作,为什么不能将类用作通用选择器?

在youtube上有很多教程,或者您可以访问jQuery文档网站。

相关问题