凌乱但工作的jQuery

Messy but Working jQuery

本文关键字:jQuery 工作      更新时间:2023-09-26

我已经为我正在做的一个小项目编写了您将在下面看到的jQuery。它工作得很好,一切都准备好了,但是,正如你所看到的,它很乱,有点……长喘气的。

我已经尝试了很多不同的方法来清理它,但我还没有像忍者那样真正地清理它。任何建议吗?提前感谢各位!

  var colspan = $(".col header span"),
      rowspan = $(".row header span"),
      topspan = $(".top header span");
  var colh2 = $(".col header h2").h2width();
  var rowh2 = $(".row header h2").h2width();
  var toph2 = $(".top header h2").h2width();
  var colwidth = 820 - colh2;
  var rowwidth = 820 - rowh2;
  var topwidth = 820 - toph2;
  colspan.css({float: 'left', width: colwidth});
  rowspan.css({float: 'left', width: rowwidth});
  topspan.css({float: 'left', width: topwidth}); 
["col", "row", "top"].forEach(function (className) {
  var str = "." + className + " header";
  var h2s = document.querySelectorAll(str + " h2");
  var spans = document.querySelectorAll(str + " span");
  var width = 820 - h2width(h2s);
  Array.prototype.forEach.call(spans, function (span) {
    span.style.float = "left";
    span.style.width = width;
  });
});

我会这样做吗?更短,但可能没有很好地记录:

$(".col header span, .row header span, .top header span").each(function(){
    $(this).css({
        float: 'left',
        width: 820 - $(this).siblings("h2").width()
    });
});

我可能会这样重写你的代码:

var conts = {
    'col': jQuery('.col header'),
    'row': jQuery('.row header'),
    'top': jQuery('.top header')
};
jQuery.each(conts, function(index, val){
    val.find('span').css({
        'float': 'left',
        'width': 820-val.find('h2').h2width()
    });
});

使用缓存主元素,然后将遍历所有应用类似的操作。

查看jQuery .each()函数的更多信息

EDIT:或者更短:

jQuery('.col header, .row header, .top header').each(function(){
    var current = jQuery(this);
    current.find('span').css({
        'float': 'left',
        'width': 820 - current.find('h2').h2width()
    });
});

直接删除重复的代码:

$.each(['.col', '.row', '.top'], function(i, cls) {
    var width = $(cls + ' header h2').h2width();
    $(cls + ' header span').css({
        float: 'left',
        width: 820 - width
    });
});

使用一个函数:

function updateStyle(name){
   var headerSpan = $('.' + name + ' header span');
   var headerH2 = $('.' + name + ' header h2');
   headerSpan.css({float: 'left', width: 820 - headerH2.h2width()});
}
updateStyle('col');
updateStyle('row');
updateStyle('top');