我正在尝试获取动态添加的div的id。 (.flak)
我使用可拖动和可投放的
我得到的只是“未定义”
这一行:
var flakId = $(this).next('.flak').attr('id');
HTML
<div class="col-md-1">
<button class="btn btn-success" id="btnAddFlak">+ Flak</button>
</div>
<div class="listElements">
<div class='elementDiv' id="1">1</div>
<div class='elementDiv' id="2">2</div>
<div class='elementDiv' id="3">3</div>
</div>
<br>
<br>
<div class="well" id="flakDiv"></div>
JS
//run function makeMov
makeMov();
//Create flak
$('#btnAddFlak').on('click', function () {
//Set flakNr
flakNr = $('.flakMiddle').last().find("span").text();
if (isNaN(flakNr)) flakNr = 1;
//Increase flakNr
flakNr++;
//create flak id
var flakId = flakNr;
//Flak HTML setup
var flak = $('<span class="deleteFlak pull-right">x</span><div class="flak nopadding" id="' + flakId + '"><div class="flakSideUp nopadding"></div><div class="flakMiddle">Flak <b><span>' + flakNr + '</span></b><p>hej</p></div><div class="flakSideDown nopadding"></div></div><br>');
//Insert flak to flakDiv
$('#flakDiv').append(flak);
//Run function makeMov
makeMov();
}); //END Create flak
//Delete flak
$(document).on('click', '.deleteFlak', function () {
//create flak id
var flakId = $(this).next('.flak').attr('id');
//Remove flak from DOM
$(this).next('.flak').remove();
$(this).remove();
}); //END Delete flak
function makeMov() {
//Make elementDiv draggable
$('.elementDiv').draggable({
revert: 'invalid',
grid: [5, 5],
containment: "document",
});
//Make listElements droppable
$('.listElements').droppable({
grid: [5, 5],
accept: '.elementDiv',
containment: "document",
tolerance: "fit",
});
//Make flakSideUp droppable
$('.flakSideUp, .flakSideDown').droppable({
grid: [5, 5],
accept: '.elementDiv',
containment: "document",
tolerance: "fit",
hoverClass: "drop-hover",
activeClass: "ui-state-highlight",
drop: function (event, ui) {
var flakId = $(this).next('.flak').attr('id');
var elId = ui.draggable.attr("id");
alert(flakId + " -> " + elId);
/*Get your element object and store into variable*/
var el = ui.draggable;
//Get position
var elpos = el.position();
var newPos = "x:" + elpos.left + " y:" + elpos.top;
}
});
}; //END function makeMOV
JS FIDDLE http://jsfiddle.net/z49sdh9v/
(按按钮添加flak,将div拖入可放置区域,警报未定义)
答案 0 :(得分:1)
这可以改变:
var flakId = $(event.target).closest('.flak').attr('id');
您可以使用event
来获取目标并遍历到最近的父级以获得所需的ID。