【问题标题】:Loop through all LI's using JQuery使用 JQuery 遍历所有 LI
【发布时间】:2014-04-01 22:11:01
【问题描述】:

我有一些可用的 JQuery 代码,但我一直在尝试将代码压缩为 for each 循环。如您所见,我有一个第四个 LI 的场景,但理想情况下我想要一个循环,所以它只是自动保持 LI 计数。我尝试了几种方法,但到目前为止都没有成功。这是我的工作代码:

$(document).ready(function($) {

//adds link around entire content inside of li
//li #1
var a = $('h2 a', '.slides li:first-child').clone();
a.removeAttr('title').html('');
$('.slides li:first-child').wrapInner(a);

//li #2
var b = $('h2 a', '.slides li:nth-child(2)').clone();
b.removeAttr('title').html('');
$('.slides li:nth-child(2)').wrapInner(b);

//li #3
var c = $('h2 a', '.slides li:nth-child(3)').clone();
c.removeAttr('title').html('');
$('.slides li:nth-child(3)').wrapInner(c);

//li #4 (if exists)
var d = $('h2 a', '.slides li:nth-child(4)').clone();
d.removeAttr('title').html('');
$('.slides li:nth-child(4)').wrapInner(d);

});

我还有一个基本的 JSFiddle 设置,您可以在其中使用现有代码等@http://jsfiddle.net/qgBHT/

感谢您的帮助。

【问题讨论】:

    标签: jquery loops for-loop foreach


    【解决方案1】:

    我相信这应该做同样的事情:

    $('.slides li h2 a').each(function(){
      var a = $(this).clone();
      a.removeAttr('title').html('');
      $(this).closest('li').wrapInner(a);
    });
    

    【讨论】:

    • 需要一个结束标签,但是是的 - 这是我的朋友。非常感谢!
    • 啊,抱歉,现在添加了。太好了,我能帮上忙。
    【解决方案2】:

    jsFiddle Demo

    您可能应该从父母进来,而不是孩子出去。因此,它可以选择 h2 元素,然后基本上用链接包装该 h2 元素,并为该元素提供链接的文本。这也得益于不会意外更改可能已附加到现有元素的任何事件。

    $('.slides li h2').each(function(){
       var a = $('a',this).detach();
       $(this).html(a.html()).wrap(a.html(""));
    });
    

    【讨论】:

      猜你喜欢
      • 2016-12-26
      • 2011-09-17
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 2016-12-02
      相关资源
      最近更新 更多