使用下面的代码,如何获取被拖动元素的id?然后,如果元素ID不等于1,则将元素恢复到原始位置?
谢谢,
<script> //DRAG AND DROP EVENTS
$(".container").delegate(".draggable","mouseenter",function() {
$(".draggable").draggable({
revert : function(event, ui) {
$(this).data("uiDraggable").originalPosition = {
top : 0,
left : 0
};
return !event;
},
start: function(event,ui) { // GET ID OF ELEMENT HERE IS NOT WORKING
var id = ui.draggable.attr("id");
console.log(id);
//GETTING ERROR Uncaught TypeError: Cannot read property 'attr' of undefined
//IF id <> 1 then revert to original position
}
});
});
</script>
答案 0 :(得分:1)
试试这个:
start: function(event, ui) {
var id = event.target.id;
console.log(id);
}
答案 1 :(得分:1)
在传递给revert选项的函数内部,this
将引用与被拖动元素对应的jQuery对象 - 您可以使用this.attr("id")
访问它的id。
附注:
event
或ui
参数,它似乎接收的唯一参数是布尔值start
回调中的ui
参数没有可拖动的属性
$(".draggable").draggable({
revert: function (event, ui) {
return (this.attr("id")==1);
}
});
div {
width:50px;
height:50px;
line-height:50px;
margin:5px;
text-align:center;
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<div id="1" class="draggable">1</div>
<div id="2" class="draggable">2</div>