Javascript 使用.bind和.unbind移动li
我正在尝试找出如何使用bind将选定的li从box1移动到box2,并从box2移动回box1。在这上面卡住了,需要一些帮助。此外,当选择一个li并通过单击“向右移动”移动到下一个框时,它们会在每次单击时堆叠。我怎样才能解决这个问题 代码: CSS: HTML:Javascript 使用.bind和.unbind移动li,javascript,jquery,html,javascript-events,Javascript,Jquery,Html,Javascript Events,我正在尝试找出如何使用bind将选定的li从box1移动到box2,并从box2移动回box1。在这上面卡住了,需要一些帮助。此外,当选择一个li并通过单击“向右移动”移动到下一个框时,它们会在每次单击时堆叠。我怎样才能解决这个问题 代码: CSS: HTML: 啤酒 水 苏打水 果汁 JSFiddle: 请查看以下代码: 我们可以简单地将代码修改如下: $(document).ready(function() { $(".box1 ul li, .box2 ul
-
啤酒
-
水
-
苏打水
-
果汁
JSFiddle:
请查看以下代码: 我们可以简单地将代码修改如下:
$(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));
});
});
});
太棒了,谢谢!绑定、解除绑定会让事情变得更麻烦吗?谢谢@MattPicca<代码>$。绑定和
$。解除绑定
将使当前代码复杂化。通常,当任何特定的事件
被其他代码段广播时,我们使用$.unbind
,我们希望避免执行我们自己的事件侦听。但在你的情况下,要求是完全不同的。好吧,我现在明白了。谢谢@vijayP的帮助,非常感谢。
.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;}
<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>
$(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));
});
});
});