我有一些工作的JQuery代码,但我一直试图将代码压缩到一个for每个循环。正如您所看到的,我有一个第4 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/。
任何帮助都是非常感谢的,谢谢。
发布于 2014-04-01 22:16:44
我认为,这种做法也应如此:
$('.slides li h2 a').each(function(){
var a = $(this).clone();
a.removeAttr('title').html('');
$(this).closest('li').wrapInner(a);
});发布于 2014-04-01 22:36:45
你可能应该从父母那里,而不是孩子出去。因此,它可以选择h2元素,然后基本上将该h2元素与链接包装在一起,并将该元素赋予链接的文本。这也有利于避免意外地改变任何可能附加到现有元素的事件。
$('.slides li h2').each(function(){
var a = $('a',this).detach();
$(this).html(a.html()).wrap(a.html(""));
});https://stackoverflow.com/questions/22797906
复制相似问题