javascript 如何删除从列表中拉出的项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9403422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove an item that is pulled away from it's list?
提问by aamiri
here is a simple question. I have a 'ul' which i have made sortable via jquery-ui's sortable() function. I want to remove elements when they are dragged off the list. The way i have it implemented works in the sense that when i drag an element away from the list it gets removed, but it also gets removed when i just rearrange the list. How do i achieve the behavior i am looking for without this unintended behavior. Below is all the code:
这是一个简单的问题。我有一个“ul”,我已经通过 jquery-ui 的 sortable() 函数对其进行了排序。当元素被拖出列表时,我想删除它们。我实现它的方式是,当我将一个元素从列表中拖出时,它会被删除,但当我重新排列列表时,它也会被删除。如果没有这种意外行为,我如何实现我正在寻找的行为。下面是全部代码:
<html>
<head>
<link type="text/css" href="jquery-ui/css/ui-lightness/jquery-ui-1.8.17.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="jquery-ui/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery-ui/js/jquery-ui-1.8.17.custom.min.js"></script>
<script type="text/javascript">
$(function(){
$('#sortme').sortable({
out: function(event, ui){
ui.item.remove();
}
});
$('#sortme').disableSelection();
});
</script>
<style>
li{
list-style-type: none;
width: 200px;
height: 50px;
border: 1px solid #000;
text-align: center;
box-sizing: border-box;
padding-top: 15px;
}
</style>
<title> jqui sort test </title>
</head>
<body>
<ul id='sortme'>
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
</body>
</html>
Thank you for your help!
谢谢您的帮助!
回答by Drew
You could try to use a variable to check if the items you are dragging is dragged out of its parent container.
您可以尝试使用变量来检查您正在拖动的项目是否被拖出其父容器。
You can use the overand outevents of the jQuery UI sortable to assign the value for this variable and then execute the removal of the dragged item on the beforeStopevent.
您可以使用jQuery UI sortable的over和out事件为该变量赋值,然后在beforeStop事件上执行拖动项的移除。
here is a demo of what I have come up with: http://jsfiddle.net/drewP/m7VJq/1/
这是我想出的演示:http: //jsfiddle.net/drewP/m7VJq/1/
let me know if it works for you.
请让我知道这对你有没有用。
回答by Z. Zlatev
I'm sure there are more than one correct way to do that but if i had to do it I would probably use a wrapper element as droppable. Why not main site container, the almighty #wrapper! Bind to drop
event of the droppable and remove the item completely. It won't stay in sortable either.
我确信有不止一种正确的方法可以做到这一点,但如果我必须这样做,我可能会使用包装元素作为可放置的元素。为什么不是主站点容器,万能的#wrapper!绑定到drop
droppable 的事件并完全删除该项目。它也不会保持可排序。