gpt4 book ai didi

javascript - 如何使用jquery查找放置目标项

转载 作者:行者123 更新时间:2023-11-30 20:52:29 24 4
gpt4 key购买 nike

我需要找出用户放置可拖动项目的元素的 id。我试过使用 var tar = event.target; 函数,但它总是返回主容器的 id,而不是我想要的元素。我怎样才能解决这个问题?这是我的代码:

$('.screenContainer').droppable({
drop: function(event, ui) {
var tar = event.target.attributes[1].nodeValue;
$('#settingsDiv').html('Item id: ' + tar);
if (!ui.draggable.hasClass('channel')) {
var Class = ui.draggable.attr("class");
var title = ui.draggable.text().trim();
var droppedItemClasses = Class.split(" ");
var droppedClass = droppedItemClasses[0];
var item = $('<div class="channel elementTable ' + Class + ' ' + droppedClass + 'Dropped" name="' + title + '" id="' + (fooCount + 1) + '" style="left: ' + droppedLeft + 'px; top: ' + droppedTop + 'px;"></div>');
$(this).append(item);
fooCount += 1;
foo();
}
}
});

编辑:这是 fiddle :https://jsfiddle.net/vaxobasilidze/zbpgf9g6/1/

最佳答案

这里有工作代码段。 $(event.target).attr('id') - 足够了

$(document).ready(function() {

$( function() {
$( "#draggable" ).draggable();
$( ".screenContainer" ).droppable({
drop: function( event, ui ) {
// Get target id
var id = $(event.target).attr('id');

// Show id in console
console.log('id:', id);

$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
});
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Droppable - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#draggable { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }
.screenContainer { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; border: 1px solid red; }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<div id="draggable" class="ui-widget-content">
<p>Drag me to my target</p>
</div>

<div id="droppable1" class="screenContainer">
<p>Drop here</p>
</div>

<div id="droppable2" class="screenContainer">
<p>Drop here</p>
</div>

<div id="droppable3" class="screenContainer">
<p>Drop here</p>
</div>

<div id="droppable4" class="screenContainer">
<p>Drop here</p>
</div>


</body>
</html>

在你的例子中使用

tar = event.originalEvent.target.id;

您总是可以在 event.targetevent.originalEvent.target 中找到 id

关于javascript - 如何使用jquery查找放置目标项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48022228/

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