【问题标题】:if() else() statement problem ... :/if() else() 语句问题... :/
【发布时间】:2011-06-10 04:56:21
【问题描述】:

有人可以帮我处理“if else 语句”吗,我遇到了这个脚本的问题:

    $('div#wrapper div.teamwrapper:odd').addClass('odd');

    $('div.teamwrapper').each(function(index){
      if($('div.teamwrapper').hasClass('odd')){
        $(this).css('top', index*35);
      }else{
        $(this).css('top', index*28);
      }
    });

我的问题是,上面的脚本只执行“if语句”中的参数。即使对象没有“奇数”类,它也会将“if 语句”中的参数应用于所有“div.teamwrapper”。谢谢。

【问题讨论】:

  • 你试过alert(),每个'if'和'else'!!
  • console.log 会更好,alert 真的不应该再用了。

标签: jquery if-statement


【解决方案1】:
  $('div#wrapper div.teamwrapper:odd').addClass('odd');

    $('div.teamwrapper').each(function(index){
      if($(this).hasClass('odd')){
        $(this).css('top', index*35);
      }else{
        $(this).css('top', index*28);
      }
    });

【讨论】:

    【解决方案2】:

    应该是

    $('div#wrapper div.teamwrapper:odd').addClass('odd');
    
        $('div.teamwrapper').each(function(index){
          if($(this).hasClass('odd')){
            $(this).css('top', index*35);
          }else{
            $(this).css('top', index*28);
          }
        });
    

    【讨论】:

      【解决方案3】:

      通过this内部函数访问对象

      $('div.teamwrapper').each(function(index){
          if($(this).hasClass('odd')){
          $(this).css('top', index*35);
          }else{
          $(this).css('top', index*28);
      }
      });
      

      【讨论】:

        【解决方案4】:

        你可以试试这个

        $('div.teamwrapper').hasClass('odd') 替换为$(this).hasClass('odd')

        这似乎比你写的更合乎逻辑。

        【讨论】:

          【解决方案5】:

          在这种情况下,最简单的方法是使用带有设置值的函数的 css 方法。你可以阅读它in the jQuery doc

          $('div#wrapper div.teamwrapper:odd').addClass('odd');
          
          $('div.teamwrapper').css('top', function(index, value){
            if ($(this).hasClass('odd')) {
              return index*35;
            } else {
              return index*28;
            }
          });
          

          如果你真的想使用 each 方法,可以这样操作:

          $('div.teamwrapper').each(function(index){
            var $me=$(this);
            if($me.hasClass('odd')){
              $me.css('top', index*35);
            }else{
              $me.css('top', index*28);
            }
          });
          

          您应该先将$(this) 的值保存到一个变量中(例如$me),然后再使用该变量,这样可以节省一些资源,而且无论如何都是一个良好的编程习惯。

          【讨论】: