假设我有以下代码:
var mainObj = {
area: $("#elementsArea"),
elements: [],
addElement: function (x, y) {
var newElement = $('<div class="element"></div>');
newElement.css("top", y);
newElement.css("left", x);
newElement.appendTo(this.area);
this.elements.push( { id: this.elements.length, x: x, y: y } );
newElement.dragabble({
stop: function () {
// What to do here?
}
});
},
updateElement: function ( element_id, x, y ) {
// Find element in this.elements table table and update x, y
},
setup: function () {
this.area.bind('click', this, function (e) {
e.data.addElement( e.offsetX, e.offsetY );
});
}
}
$(document).ready( function () { mainObj.setup() } );
HTML和CSS是无关紧要的,其他属性和功能也是如此。我想要做的是在可拖动事件停止后以某种方式将新位置传递给 updateElement
方法,这样我就可以更新 elements 表中的对象,类似于我对 < em>点击事件。
我该怎么做,或者我在代码设计上做了什么不好的事情吗?
最佳答案
停止函数有两个参数,我认为您可以从它们中获取更新所需的信息,如下所示:
http://api.jqueryui.com/draggable/#event-stop
newElement.dragabble({
stop: function (event, ui) {
var element_id = ui.helper.attr('id');// or get id as you want
// ui.position or ui.offset try what you need
this.updateElement(element_id, ui.position.top, ui.position.left);
}
});
(尚未仅测试想法模式)
经过测试和改进的版本:
addElement: function (x, y) {
var self = this;// self is an alias for this
var id = 'id_' + this.elements.length;// create unique ID
var newElement = $('<div class="element"></div>');
newElement.css("top", y);
newElement.css("left", x);
newElement.attr('id', id);//add ID for element
newElement.appendTo(this.area);
this.elements.push( { id: id, x: x, y: y } );
newElement.dragabble({
stop: function () {
var element_id = ui.helper.attr('id');
// ui.position or ui.offset try what you need
self.updateElement(element_id, ui.position.top, ui.position.left);
}
});
},
关于javascript - 将参数或包含对象传递给 jQuery UI 可拖动事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35769839/