Javascript 从可拖动元素获取ID值
我有以下代码:Javascript 从可拖动元素获取ID值,javascript,draggable,jquery-ui-draggable,Javascript,Draggable,Jquery Ui Draggable,我有以下代码: $( init ); function init() { $(".Arrastrable").draggable({ stop: function(event, ui) { var pos = $(this).position(); $("div#stop").text("Pos: "+ pos.left + ", " + pos.top); } }); } 在HTML中,我有以下内容: <body> <div id
$( init );
function init() {
$(".Arrastrable").draggable({
stop: function(event, ui) {
var pos = $(this).position();
$("div#stop").text("Pos: "+ pos.left + ", " + pos.top);
}
});
}
在HTML中,我有以下内容:
<body>
<div id="contenido" style="height: 400px;">
<form name="Registro" action="Guardar" method="post" id="Registro">
<table
<tr>
<td>
<div class="Arrastrable">
<img src="./css/Imagenes/mesa.png" id="mesa1"></img>
</div>
<div class="Arrastrable">
<img src="./css/Imagenes/mesa.png" id="mesa2"></img>
</div>
</td>
</tr>
</table>
</form>
</body>
我需要获取实际可拖动元素的ID值,我尝试使用$ui.item.attrid,但没有成功。我不知道是否必须添加其他方法或什么。我不记得该属性是如何调用的,我将在JSFIDLE中查找它并在此处进行编辑,但您可以这样做:
$(".Arrastrable").draggable({
stop: function(event, ui) {
var pos = $(this).position();
console.dir(event);
console.dir(ui);
$("div#stop").text("Pos: "+ pos.left + ", " + pos.top);
}
});
并检查GoogleWebDeveloperTools或firebug中的属性
好的,检查一下,您可以在控制台中看到事件和ui对象的属性,以及在event.target.firstChild.id中查找的属性,或者使用jQuery查看。draggable没有ui.item。正在拖动的元素是div.arrastable,它在代码中没有id。如果要拖动图像的id,请使用$img,即this.attrid
工作演示:
$(init);
function init() {
$(".Arrastrable").draggable({
stop: function(event, ui) {
var imgId = $("img", this).attr("id");
var pos = $(this).position();
$("#stop").text("Pos: " + pos.left + ", " + pos.top + ". Id: " + imgId);
}
});
}