Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

jquery - Use function with arguments within .each()

I want to use single function for different lists changin the arguments.

Statement like this $( ".animals li" ).each(color); works. However, as I try to pass parameters, even empty, does not work $( ".animals li" ).each(color());

In my case I want to get function, which changes the color of the odd elements (color different). Any way?

<ul class="animals">
            <li>cat</li>
            <li>hamster</li>
            <li>dog</li>
            <li>racoon</li>
            <li>rat</li>
</ul>

<ul class="plant">
            <li>pine</li>
            <li>oak</li>
            <li>fir</li>
            <li>birch</li>
            <li>palm </li>
</ul>

$( document ).ready(function(){
      $( ".animals li" ).each(color(ind, el, "green"));
    $( ".plant li" ).each(color(ind, el, "red"));
    
    
  function color( index, element, text_color ) { 
        if( index % 2 != 0 ) { 
          $( this ).css( "color", text_color ); 
        }
      }
});

https://jsfiddle.net/Nata_Hamster/sp4k2wat/

question from:https://stackoverflow.com/questions/65909678/use-function-with-arguments-within-each

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot pass the parameters like that. You need to pass it like:

$( ".animals li" ).each((ind, el) => color(ind, el, "green"));

That will do it. However, you need to fix your color function to not use 'this':

function color( index, element, text_color ) { 
        if( index % 2 != 0 ) { 
          $( element ).css( "color", text_color ); 
        }
      }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...