Is it possible to beautify this JavaScript code?

前端 未结 3 1055
一生所求
一生所求 2020-12-12 06:54

I have done my research but i cant find anything useful that are related to my question.

Original JavaScript Code

$(\"#furniture1\")         


        
相关标签:
3条回答
  • 2020-12-12 07:35

    Just separate selectors with ,.

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

    Example

    $("#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 dynamic you need a loop. You can just decrease the code written in the loop like

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

    Or as @Satpal have mentioned in the comments you can add a common class for all elements and use that class to bind the event handler like.

    $(".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'>

    0 讨论(0)
  • 2020-12-12 07:39

    Option 1: Use event delegation. This solution is pure javascript:

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

    Demo

    $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>


    Option 2 [*]: If you do need to use jQuery, you can either use event delegation, or use a class for calling the same function on when keyup is captured in any element on that class:

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

    And assign the .keyup-capturer class to all the #furniture-x and #color-x element IDs. I don't recommend this approach anymore. See the discussion below.


    [*] Some observations:

    • Use event delegation over class-based listeners for best results.
    • Don't use for loops or forEach or map to attach event handlers. You'll just be adding a lot of event handlers, and eventually, you'll find your page growing slower with more complexity.
    • Avoid attaching listeners to a set of selected elements (such as shown in Option #2). See this line in jQuery's source code. jQuery hides the implementation detail from you, but under the hoods, it still attaches one event listener per element. So, if you're using non-ID-based selectors such as class selectors $('.c1'), or attribute selectors $('[disabled]'), etc), keep in mind this fact. Thanks to @t.niese for pointing this out in the comments.
    0 讨论(0)
  • 2020-12-12 07:55

    try adding a class furniture on all furnitures, class color on all colors, and so on... so that you can select them by group:

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

    or you can pass your function directly:

    let furnitures = document.querySelectorAll('.furnitures');
    furnitures.forEach((furniture) => {
       furniture.addEventListener('keyup', samefunction)
    })
    
    0 讨论(0)
提交回复
热议问题