使用.bind和.unbind移动li

时间:2016-11-03 05:35:55

标签: javascript jquery html javascript-events

我试图找出如何使用bind将选定的li从box1移动到box2,然后从box2移回box1。坚持这一点,需要一些帮助。此外,当选择li并通过单击"向右移动"移动到下一个框时,它们会在每次单击时叠加。我该如何解决这个问题。

代码:

 $(document).ready(function(){
            $(".box1 ul li").click(function(){
               if($(this).hasClass("active-li")==true)
               {
                    $(this).removeClass("active-li");
               }
               else
               {
                    $(this).addClass("active-li");
               }
            });
            $(".box1 ul li").click(function(){
                 var x=$(this).data("drink");
                 $("#btt1").click(function(){
                    $(".box2 ul").append(x);
                    $(x).bind("click", bindLi);


                }); 
            });
            $(x).bind("click", bindLi);
        });


        function bindLi(){
            alert("hello");
        }

CSS:

        .box1{border:1px solid black; width:200px; height:200px; float:left; margin-top:100px; margin-left:50px;}
        .box2{border:1px solid black; width:200px; height:200px; float:left; margin-top:100px; margin-left:100px;}
        .button-container{width:80px; height:30px; float:left; margin-top:200px; margin-left:100px;}
        .active-li{background-color:yellow;}
        ul li:hover{cursor:pointer;}

HTML:

  <div class="box1" id="box1">
        <ul>
            <li data-drink="beer">
               Beer 
            </li>
            <li data-drink="water">
               Water 
            </li>
            <li data-drink="soda">
                Soda
            </li>
            <li data-drink="juice">
                Juice
            </li>
        </ul>
    </div>
    <div class="button-container">
        <input type="button" id="btt1" name="btt1" value="Move Right" />
        <input type="button" id="btt2" name="btt2" value="Move Left" />
    </div>
    <div class="box2" id="box2">
        <ul></ul>
    </div>

的jsfiddle:

https://jsfiddle.net/fgo455zt/

1 个答案:

答案 0 :(得分:2)

请看下面的代码:

https://jsfiddle.net/fgo455zt/5/

我们可以简单地按如下方式编写代码:

$(document).ready(function() {
  $(".box1 ul li, .box2 ul li").click(function() {
    $(this).toggleClass("active-li"); //highlight the clicked li
  });

  $("#btt1, #btt2").click(function() {
    var sourceUL = null;
    var targetUL = null;
    //depending upon which button clicked we are moving selected li to and from source to target UL
    if ($(this).attr("id") == "btt1") {
      sourceUL = $(".box1 ul");
      targetUL = $(".box2 ul");
    } else {
      sourceUL = $(".box2 ul");
      targetUL = $(".box1 ul");
    }

    $(sourceUL).find("li.active-li").each(function() {
      $(this).removeClass("active-li"); //removing the active class before moving the li
      $(targetUL).append($(this));
    });
  });

});