很抱歉打扰了SO社区,但我必须继续我的生活:有一个潜在的无限可点击图像列表(将来会扩展),当点击这些图像时,最多可以填满两个单独元素中的点。下一步不仅是填充下一个未填充的元素,而且如果他们再次从列表中选择,那么它将返回到位置 1,替换旧图像。我想不出应用正确逻辑来实现这一目标的方法。这是我到目前为止所拥有的。
<div class="spot-1"></div><!--start here -->
<div class="spot-2"></div><!--then here -->
<div class="img-wrap">
<div><img class="PutinSpot"src="someIMG0.jpg" alt="dufuq?"></div>
<div><img class="PutinSpot"src="someIMG1.jpg" alt="dufuq?"></div>
<div><img class="PutinSpot"src="someIMG2.jpg" alt="dufuq?"></div>
<div><img class="PutinSpot"src="someIMG3.jpg" alt="dufuq?"></div>
<div><img class="PutinSpot"src="someIMG4.jpg" alt="dufuq?"></div>
</div><!--potentially^^^^^ infinite list-->
这是它的 Jquery。
$(document).ready(function () {
$('.PutinSpot').click(function(){
var CloneBadge = $(this).clone()
$(CloneBadge).appendTo('.spot-1').addClass('occupado');
if ($('.spot-1 div').find('> img').length) {
$(this).appendTo('.spot-2');
}
});
});
澄清一下。 该列表需要能够无限增长。但我希望它将 img-wrap div 中单击的图像放入 Spot-1 中,然后将下一个图像单击到 Spot-2 中,一旦满了,让它检查它们是否都已满,如果是,则追加到 Spot-又1。这会是一个循环吗?开关机壳?
最佳答案
编程时尝试考虑数据如何流动。操作 DOM 来实现最终行为是次要问题。假设我正确理解了要求,让我们这样重新表述您的问题:
There's a variable sized list of images from which the user can select a maximum count of two. The currently selected images will be displayed in 2 separate spots
在图像已位于 DOM 中的上下文中解决此问题的方法如下所示:
$(document).ready(function() {
$('.PutinSpot').click(function() {
selectImage(this);
});
});
var selectedImages = [];
function selectImage(imageEl) {
// Remove an element from the front of the array if length is 2
// This way the array will allways have 2 elements maximum
if (selectedImages.length == 2) selectedImages.shift();
selectedImages.push(imageEl);
// For each selected image, find the correct div and
// replace the content completely with the correct image
selectedImages.forEach(function(img, i) {
var targetDiv = $('.spot-' + (i + 1));
targetDiv.html($(img).clone());
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Selected Image 1: <div class="spot-1"></div>
<!--start here -->
Selected Image 2: <div class="spot-2"></div>
<!--then here -->
<hr/>
<div class="img-wrap">
<div><img class="PutinSpot" src="http://placehold.it/50x50/000000" alt="dufuq?"></div>
<div><img class="PutinSpot" src="http://placehold.it/50x50/ff0000" alt="dufuq?"></div>
<div><img class="PutinSpot" src="http://placehold.it/50x50/ffff00" alt="dufuq?"></div>
<div><img class="PutinSpot" src="http://placehold.it/50x50/f110f2f" alt="dufuq?"></div>
<div><img class="PutinSpot" src="http://placehold.it/50x50/0000ff" alt="dufuq?"></div>
</div>
关于javascript - 克隆然后从可能无限的列表中追加一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46700963/