【问题标题】:Use function with arguments within .each()在 .each() 中使用带参数的函数
【发布时间】:2021-04-30 17:29:26
【问题描述】:

我想使用单个函数来改变参数的不同列表。

$( ".animals li" ).each(color); 这样的声明有效。 但是,当我尝试传递参数时,即使是空的,也不起作用$( ".animals li" ).each(color());

在我的情况下,我想获得改变奇数元素颜色(颜色不同)的函数。 有办法吗?

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

【问题讨论】:

    标签: jquery each


    【解决方案1】:

    你不能这样传递参数。你需要像这样传递它:

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

    这样就可以了。但是,您需要修复颜色函数以不使用“this”:

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

    【讨论】:

      猜你喜欢
      • 2015-11-09
      • 1970-01-01
      • 2016-11-13
      • 2015-12-18
      • 2021-10-10
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      相关资源
      最近更新 更多