gpt4 book ai didi

javascript - Jquery 获取未定义

转载 作者:行者123 更新时间:2023-11-30 00:23:06 27 4
gpt4 key购买 nike

我正在尝试获取动态添加的 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/

(按下按钮添加高炮,将div拖入可放置区域,警报未定义)

最佳答案

这是可以改变的:

var flakId = $(event.target).closest('.flak').attr('id');

您可以利用event 获取目标并向上遍历到最近的父级以获得所需的id。

Check the fiddlewa.

关于javascript - Jquery 获取未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32439613/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com