簡體   English   中英

如何循環和縮短代碼

[英]how to loop and shorten the code

我有類似的代碼,但只有一點點不同。 如何縮短下面的代碼?

下面的例子

var sms = document.getElementsByClassName("class-two");
sms.forEach(function(e) {
  e.style.width = 200 + 'px';
});

var sms = document.getElementsByClassName("class-one");
sms.forEach(function(e) {
  e.style.height = 100 + 'px';
});

上面的區別只是第一class-one和第二class-two以及兩行e.style.width = 200 + 'px'; e.style.height = 100 + 'px'; ,我可以在這里使用循環嗎?

遵循DRY(不要重復自己)原理 ,您可以編寫一個函數來封裝您的冗余代碼:

function setWidth(cls, attr, pixels) {
  Array.from(document.getElementsByClassName(cls)).forEach(function(e) {
    e.style[attr] = pixels + 'px';
  });
}
setWidth("class-two", "width", 200);
setWidth("class-one", "height", 100);

使用Array#forEach並創建一個可以使用類,樣式屬性和值..調用的函數。

function setThings(cls, attr, value) {
    [].forEach.call(document.getElementsByClassName(cls), function(el) {
        el.style[attr] = value;
    });
}
setThings("class-two", 'width', '200px');
setThings("class-one", 'height', '100px');

但是,即使在解決問題后仍濫用forEach

[].forEach.call(document.getElementsByClassName("class-two"), function(e) {
  e.style.width = '200px';
});

[].forEach.call(document.getElementsByClassName("class-one"), function(e) {
  e.style.height = '100px';
});

實際上是較短的代碼,除非函數(setThings)用單個字符命名,否則第一個答案較短

在執行操作時直接在元素上設置CSS樣式被認為是不好的做法,這是不必要的。 您可以通過智能地使用CSS來極大地簡化代碼,從而將JS的數量減少到實質上僅一行來切換上級元素上的類,從而驅動子元素的寬度或高度,從而消除了對循環或函數的需求。 您將減少編寫,調試和維護的代碼。 本質上,不是讓您自己在JS中查找具有特定類的所有元素,而是讓CSS引擎執行此操作,這就是它的目的!

 const topElement = document.getElementById('top'); const buttonElement = document.getElementById('button'); function toggle() { topElement.classList.toggle('narrow'); } buttonElement.addEventListener('click', toggle); 
 .class-one, .class-two { width: 300px; height: 16px; } .class-one { background: red; } .class-two { background: blue; } .narrow .class-one { width: 200px; } .narrow .class-two { height: 100px; } 
 <div id="top"> <div class="class-one"></div> <div class="class-two"></div> </div> <button id="button">Toggle</button> 

@qxz答案似乎最好。 但是,如果要避免函數調用,請參考以下內容:

[].forEach.call(document.querySelectorAll('.class-two,.class-one'), function(e) {
  if (e.className.includes("class-two")) {
    e.style.width = "200px";
  };
  if (e.className.includes("class-one")) {
    e.style.height = "100px";
  };
});

為你擺弄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM