簡體   English   中英

可以美化此JavaScript代碼嗎?

[英]Is it possible to beautify this JavaScript code?

我已經進行了研究,但是找不到與我的問題有關的任何有用信息。

原始JavaScript代碼

$("#furniture1").keyup(function(){
  samefunction();
});
$("#furniture2").keyup(function(){
  samefunction();
});
$("#furniture3").keyup(function(){
  samefunction();
});

$("#color1").keyup(function(){
  samefunction();
});
$("#color2").keyup(function(){
  samefunction();
});
$("#color3").keyup(function(){
  samefunction();
});

我只能提出這個解決方案,有沒有更好的解決方案?

var index_no = 0;

for(var i=1; i<=3; i++)
{
    index_no++;
    var name = '#furniture';
    name += index_no;

    $(name).keyup(function () {
        samefunction();
    });

    var name = '#color';
    name += index_no;

    $(name).keyup(function () {
        samefunction();
    });
}

只有獨立的選擇,

$("#furniture1, #furniture2, #furniture3, #color1, #color2, #color3").keyup(function(){
  samefunction();
});

 $("#furniture1, #furniture2, #furniture3, #color1, #color2, #color3").keyup(function(){ console.log(`Fired from the input ${this.id}`); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="furniture1"> <input id="furniture2"> <input id="furniture3"> 

對於動態,您需要一個循環。 您可以減少循環中編寫的代碼,例如

for(var i = 1; i <= 3; i++)
{
    $(`#furniture${i}, #color${i}`).keyup(function () {
        samefunction();
    });
}

或者,正如@Satpal在注釋中提到的那樣,您可以為所有元素添加一個通用類,並使用該類來綁定事件處理程序。

 $(".someClass").keyup(function(){ console.log(`Fired from the input ${this.id}`); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="furniture1" class='someClass'> <input id="furniture2" class='someClass'> <input id="furniture3" class='someClass'> 

選項1:使用事件委托。 此解決方案是純javascript:

document.querySelector('body').addEventListener('keyup', (e) => {
  if (e.target.classList.contains('keyup-capturer')) {
    somefunction();
  }
});

演示版

 $ctr = document.getElementById('counter'); document.querySelector('body').addEventListener('keyup', (e) => { if (e.target.classList.contains('keyup-capturer')) { somefunction(); } }); function somefunction() { console.log(`Fired from the input ${this.id}`); $ctr.innerHTML = parseInt($ctr.innerHTML, 10) + 1; }; 
 <input id="furniture1" class="keyup-capturer"> <input id="furniture2" class="keyup-capturer"> <input id="furniture3" class="keyup-capturer"> <input id="color1" class="keyup-capturer"> <input id="color2" class="keyup-capturer"> <input id="color3" class="keyup-capturer"> <div>Key Ups: <span id="counter">0</span></div> 


選項2 [*] :如果確實需要使用jQuery,則可以使用事件委托,也可以使用一個class在該類的任何元素中捕獲keyup時調用相同的函數:

$('.keyup-capturer').keyup(function() { samefunction(); });

並將.keyup-capturer類分配給所有#furniture-x#color-x元素ID。 我不再推薦這種方法。 請參閱下面的討論。


[*]一些觀察:

  • 對基於類的偵聽器使用事件委派以獲得最佳結果。
  • 不要使用for循環或forEachmap來附加事件處理程序。 您將只添加許多事件處理程序,最終,您會發現頁面的增長速度越來越慢,而且復雜性更高。
  • 避免將偵聽器附加到一選定的元素上(如選項2中所示)。 請參閱jQuery的源代碼中的這一行 jQuery向您隱藏了實現細節,但在幕后,它仍然為每個元素附加一個事件偵聽器。 因此,如果您使用的是非基於ID的選擇器,例如類選擇器$('.c1')或屬性選擇器$('[disabled]')等),請記住這一事實。 感謝@ t.niese在評論中指出這一點

嘗試在所有furniture上添加類別furniture在所有color上添加類別顏色,依此類推...以便您可以按組選擇它們:

let furnitures = document.querySelectorAll('.furnitures');
furnitures.forEach((furniture) => {
   furniture.addEventListener('keyup', function() {
      // your code here
   })
})

或者您可以直接傳遞函數:

let furnitures = document.querySelectorAll('.furnitures');
furnitures.forEach((furniture) => {
   furniture.addEventListener('keyup', samefunction)
})

暫無
暫無

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

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