代码之家  ›  专栏  ›  技术社区  ›  Marlon Creative

jQuery每个循环-使用变量

  •  5
  • Marlon Creative  · 技术社区  · 16 年前

    我有一份产品清单。每个产品都有一个标题和一个评论链接。目前,标题直接链接到单个产品页面,而评论链接则转到其他地方。

    我想使用jqueryeach循环遍历每个li,从标题(第一个链接)中获取href,并将其应用于审阅链接(第二个链接),这样它们都指向产品页面。

    简化代码如下:

    <ul>
       <li><a href="product1.html">Product 1</a><a href="review1.html">Review 1</a></li>
       <li><a href="product2.html">Product 2</a><a href="review2.html">Review 2</a></li>
       <li><a href="product3.html">Product 3</a><a href="review3.html">Review 3</a></li>
    </ul>
    

    $("li").each(function(){
       var link = $("a:eq(0)").attr('href');
       $("a:eq(1)").attr("href", link);
    });
    

    但它总是使用相同的变量“link”。

    有人能帮我吗?

    5 回复  |  直到 16 年前
        1
  •  11
  •   Gabe    16 年前

    我路过 this 作为参数来定义 each() 循环。在每次迭代中, 这

    $("li").each(function(){
       var link = $("a:eq(0)", this).attr('href');
       $("a:eq(1)", this).attr("href", link);
    });
    
        2
  •  3
  •   Svante Svenson    16 年前
    $("li").each(function(){
       var link = $(this).find("a:eq(0)").attr('href');
       $(this).find("a:eq(1)").attr("href", link);
    });
    
        3
  •  1
  •   Kent    16 年前

    另一个避免使用 .each 完全是将函数作为第二个参数传递给 .attr .

    此项工作如下:

    $('li').find('a:nth-child(2)').attr('href', function(index, href) {
        return $(this).prev('a').attr('href'); // use previous sibling's href
    });
    

    href 属性指定给该函数的结果。函数将被传递参数:第一个参数是它在匹配集中的索引( $('li a:nth-child(2)') 这里),第二个是属性的当前值。在您的特定情况下,您也不关心这两个问题,但通常需要基于属性的当前值来转换属性,这样就很方便了。

    .每个 .

        4
  •  0
  •   PetersenDidIt    16 年前

    这是因为你没有使用 li 作为你的 a 选择:

    试试这个:

    $("li").each(function(){
        var a = $('a',this);
        var link = a.filter(":eq(0)").attr('href');
        a.filter(":eq(1)").attr("href", link);
    });
    
        5
  •  0
  •   David Neale    16 年前

     $("li").each(function(){
        var link = $("a:eq(0)", this).attr('href');
     $("a:eq(1)", this).attr("href", link);
      });