如何随机选择图像并将其转到另一个空列表?

时间:2017-01-25 00:25:10

标签: jquery html css random append

我有一个不同颜色的图像的无序列表,我希望它随机选择2个图像并转到另一个列表,我知道appendTo和Math.Random会做的伎俩但我不知道如何实现它可以你帮我吗?

这里是小提琴和代码

        <div class="row">
          <div class="col-md-6">
            <ul class="imageList">
              <li><img class="swapimage"  src="https://dummyimage.com/200x200/000/fff" alt=""></li>
              <li><img class="swapimage"  src="https://dummyimage.com/200x200/ffaa00/fff" alt=""></li>
              <li><img class="swapimage" src="https://dummyimage.com/200x200/ff00d5/fff" alt=""></li>
              <li><img class="swapimage" src="https://dummyimage.com/200x200/30c7db/fff" alt=""></li>
            </ul>
          </div>

          <div class="col-md-6">
            <ul class="randomList">
                <li></li>
                <li></li>
                <li></li>
                <li></li>
              </ul>
          </div>
        </div>
        <input class="main-button" type="button" value="swap" id="swapBtn" name="swapBtn">


$('#swapBtn').on('click', function(){
    $('.swapimage').prependTo('.randomList li');
});

https://jsfiddle.net/uw5cvz8z/

1 个答案:

答案 0 :(得分:0)

有点晚了......带了这个新手一段时间。我将如何做到这一点:

len = $(".swapimage").length

$('#swapBtn').on('click', function(){
	number = Math.floor(Math.random() * len);
    do {
    	number2 = Math.floor(Math.random() * len);
    } while (number2 == number);
    
    $('.randomList li').eq(number).replaceWith( $('.swapimage').eq(number) )
    $('.randomList li').eq(number2).replaceWith( $('.swapimage').eq(number2) )
});
.imageList {  margin-bottom: 100px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input class="main-button" type="button" value="swap" id="swapBtn" name="swapBtn">
  <div class="row">
              <div class="col-md-6">
                <ul class="imageList">
                  <li><img class="swapimage"  src="https://dummyimage.com/200x200/000/fff" alt=""></li>
                  <li><img class="swapimage"  src="https://dummyimage.com/200x200/ffaa00/fff" alt=""></li>
                  <li><img class="swapimage" src="https://dummyimage.com/200x200/ff00d5/fff" alt=""></li>
                  <li><img class="swapimage" src="https://dummyimage.com/200x200/30c7db/fff" alt=""></li>
                </ul>
              </div>
    
              <div class="col-md-6">
                <ul class="randomList">
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                  </ul>
              </div>
            </div>

JSfiddle