使用JQuery遍历所有LI
我有一些正在工作的JQuery代码,但我一直在尝试将代码压缩为一个for-each循环。正如你看到的,我有一个第四个LI的场景,但理想情况下我想要一个循环,所以它只是自动保持LI计数。我试过几种方法,但迄今为止没有成功。这是我的工作代码:使用JQuery遍历所有LI,jquery,loops,for-loop,foreach,Jquery,Loops,For Loop,Foreach,我有一些正在工作的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'
$(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);
});
我还有一个基本的JSFIDLE设置,您可以在其中使用现有代码,等等@
非常感谢您的帮助。我相信这也会起到同样的作用:
$('.slides li h2 a').each(function(){
var a = $(this).clone();
a.removeAttr('title').html('');
$(this).closest('li').wrapInner(a);
});
你可能应该从父母那里进去,而不是从孩子那里出去。因此,可以选择h2元素,然后基本上用链接包装该h2元素,并为该元素提供链接文本。这还得益于不会意外更改可能已附加到现有元素的任何事件
$('.slides li h2').each(function(){
var a = $('a',this).detach();
$(this).html(a.html()).wrap(a.html(""));
});
需要一个结束标记,但是的-这是一个开始,我的朋友。非常感谢!啊,对不起,现在补充说。我能帮上忙真是太好了。