问题
I am using jqueryui sortable widget. I need to get the current dragged element's data attribues. $(this).data('attribute_name') is not working here. I have also tried some other methods, but not getting the correct result.
HTML
<ul class="draggable-item" style="min-height:10px;">
<li data-parent="31" data-id="81" class="ui-state-default">Label</li>
<li data-parent="31" data-id="86" class="ui-state-default">Max Value</li>
<li data-parent="31" data-id="83" class="ui-state-default">Unit</li>
<li data-parent="31" data-id="84" class="ui-state-default">Warning Level High</li>
<li data-parent="31" data-id="85" class="ui-state-default">Warning Level Low</li>
</ul>
JS
$(document).ready(function() {
$(".draggable-item").sortable({
start: function( event, ui ) {
//Here i need to get current dragged element's 'parent' attribue.
//console.log(ui.item[0].attributes); - Here i got the entire attribute values in an array. But the order of the array is different in browsers.
},
}).disableSelection();
});
回答1:
Try $(ui.item).data('attribute_name');
or $(event.currentTarget).data('attribute_name');
回答2:
I'm using at UPDATE event:
update: function (event, ui) {
var attr_id = ui.item.attr('data-id');
}
回答3:
Using $(this)
will give you the element on which the sortable is initialized. Refer the Sortable Documentation . The current sortable item is stored in ui
object and you can access it using ui.item
.
So you can access any attribute of current sortable item by applying functions or methods on ui.item
. Prefer using $(ui.item)
.
Demo : http://jsfiddle.net/lotusgodkk/GCu2D/173/
$(document).ready(function () {
$(".draggable-item").sortable({
start: function (event, ui) {
var attr = $(ui.item).attr('data-parent');
},
}).disableSelection();
});
来源:https://stackoverflow.com/questions/24228311/jquery-sortable-how-to-get-current-dragged-element-attribute