0

I want to refactor these code, but i don't know how to implement?

Original code:

$('#members_all').click(function(){
    if(this.checked){
        $(".members").each(function(){
            this.checked = true;
        });
    } else {
        $(".members").each(function(){
            this.checked = false;
        });
    }
});

    $('#games_all').click(function(){
      if(this.checked){
        $(".games").each(function(){
            this.checked = true;
        });
    } else {
        $(".games").each(function(){
            this.checked = false;
        });
    }
}); 

My refactor idea:

  var arr = ["members","games"];
  for(var i=0; i< arr.length;i++){
       $('#'+arr[i]+'_all').click(function(){
           $("."+arr[i]).each(function(){this.checked =($('#'+arr [i]+'_all').attr("checked") == "checked");});
       });

  }

but test in browser, I got wrong result.

敬錞 潘
  • 852
  • 1
  • 14
  • 29
  • 1
    You have the right (or at least, *a* right) idea. See the linked question's answers for why the code doesn't work (`i` is equal to `arr.length` by the time the click handlers run) and what to do about it. – T.J. Crowder Nov 02 '18 at 09:29
  • do you mean that all about 'function(){...}' callback must change using createfunc() to replace? – 敬錞 潘 Nov 02 '18 at 09:50
  • There are several different solutions (all of which work) in the answers to that question. If you're targeting only modern browsers, just changing `var` to `let` in your existing code would fix it. If not, one of the other solutions... – T.J. Crowder Nov 02 '18 at 09:56

0 Answers0