问题:如何从列表中克隆每个图像并将它们“粘贴”到另一个列表中?
我已经搜索过,但没有找到任何足够接近我的解决方案的解决方案。
简短说明:我正在创建一个带有缩略图的幻灯片(jQuery 库:Slippry Slider)。我希望缩略图能够根据幻灯片的数量动态工作。
首先我有一些包含幻灯片的 HTML:
<ul id="thumbnails">
<li>
<a href="#slide1">
<img src="img/image-1.jpg" alt="This is caption 1">
</a>
</li>
<li>
<a href="#slide2">
<img src="img/image-2.jpg" alt="This is caption 2">
</a>
</li>
<li>
<a href="#slide3">
<img src="img/image-4.jpg" alt="And this is some very long caption for slide 4.">
</a>
</li>
现在我想为缩略图创建包装元素,首先是 div
,然后是 ul
-element:
// Create thumb-wrapping-elements
$('.demo_wrapper').append('<div class="thumb-box"></div>');
$('.thumb-box').append('<ul class="thumbs"></ul>');
我想检查上面的 HTML 中有多少张幻灯片:
// How many thumbs? Check how many slides there is.
var count = $("#thumbnails li").length;
创建正确数量的 li 元素并设置正确的宽度和值:
// Loop through and create li-elements and links
for (var thumbcounter = 0; thumbcounter < count; thumbcounter++) {
// Whats the width of each thumb?
var thumbwidth = (100/count) + '%';
thumburl = thumbcounter + 1;
$('.thumbs').append('<li><a href="#' + thumburl + '" data-slide="' + thumburl + '" style="width:' + thumbwidth + ';">
在这里,我想循环浏览上面 ul#thumbnails li a 中的每张幻灯片图像,并在此处打印它们。我到底该怎么做? :)
</a></li>');
};
在此处查看所有代码:http://jborg.se/dev/slippry/demo/test.html
现在“a”位于每个 a 元素内,只是为了使它们可见。
编辑:
使拇指宽度更有效,感谢下面的回答。
这就是我想要的上面 jQuery 循环的输出(现在我一切都正确,除了图像 - 我不知道如何从 HTML 复制并在此处打印为每个缩略图):
<div class="thumb-box">
<ul class="thumbs">
<li>
<a href="#1" data-slide="1">
<img src="img/image-1.jpg" alt="This is caption 1">
</a>
</li>
<li>
<a href="#2" data-slide="2">
<img src="img/image-2.jpg" alt="This is caption 2">
</a>
</li>
<li>
<a href="#4" data-slide="3">
<img src="img/image-4.jpg" alt="And this is some very long caption for slide 4.">
</a>
</li>
</ul>
</div>
最佳答案
类似这样的东西吗?
$(document).ready(function() {
var html = '<div class="thumb-box"><ul class="thumbs"></ul></div>';
$('.demo').append(html);
var count = $("#thumbnails li").length;
var width = (100.00/count) + '%';
var counter = 0;
$('#thumbnails li').each(function() {
counter++;
var newItem = '<li>';
newItem += '<a href= "' + $(this).find('a').attr('href') + '" ';
newItem += 'data-slide="' + counter + '">';
newItem += '<img src="' + $(this).find('img').attr('src') + '" alt="' + $(this).find('img').attr('alt') + '"/>';
newItem += '</a></li>';
$('ul.thumbs').append(newItem);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ORIGINAL<br/>
<ul id="thumbnails">
<li>
<a href="#1" data-slide="1">
<img src="img/image-1.jpg" alt="This is caption 1"/>
</a>
</li>
<li>
<a href="#2" data-slide="2">
<img src="img/image-2.jpg" alt="This is caption 2"/>
</a>
</li>
<li>
<a href="#4" data-slide="3">
<img src="img/image-4.jpg" alt="And this is some very long caption for slide 4."/>
</a>
</li>
</ul>
<br/>
DEMO
<div class="demo">
</div>
关于javascript - 克隆每个,附加到每个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32974045/