【发布时间】:2020-04-17 18:26:21
【问题描述】:
我意识到这个问题与其他人发布的问题相似,但我希望有人可以帮助我解决这个问题:
我在使用 JQuery 拖放的可放置项目中有一个 select 元素,该元素在拖动时被克隆。该元素有一个 ID select,但我需要该 ID 是唯一的,这样我才能访问放置区域中每个框的不同选定选项。
在拖放区域下方,您会看到选择框 ID,每当拖动新块时,我想要的输出是 select_1、select_2、select_3 等
现在,左侧有一个 id 为“select”的原始选择框,我想为放置区域中的选择框动态创建 ID。
我想知道为放置区内的每个选择框赋予其唯一 ID 的最佳方法是什么?
这样我最终可以提取选定的值(如上图所示的二、三、二、三)
期望的输出
select_1 TWO
select_2 THREE
select_3 TWO
select_4 THREE
$(document).ready(function() {
var dragOpts = {
helper: 'clone',
zIndex: 10
},
dropOpts = {
tolerance: 'fit',
drop: function(e, ui) {
if (ui.draggable.hasClass('div-source')) {
var cloneDiv = ui.draggable.clone(),
cloneDragOpts = {
containment: 'parent'
};
cloneDiv.css({
position: 'absolute',
top: ui.offset.top - $(this).offset().top,
left: ui.offset.left - $(this).offset().left
}).draggable(cloneDragOpts);
$(this).append(cloneDiv);
}
}
};
$('#source div').each(function(index) {
$(this).draggable(dragOpts);
});
$('#target').droppable(dropOpts);
});
/*
Experimenting with printing the new select IDs
Once dragged into the drop zone
*/
function drop(event) {
$("#target select").attr("id", (index, oldId) => oldId + "_" + (index + 1))
var IDs = $("#target select[id]")
.map(function() {
return this.id;
})
.get();
document.getElementById("inside_drop_zone").innerHTML = IDs.join(", ")
}
#source {
width: 150px;
height: 100px;
overflow: auto;
float: left;
border: 2px solid #696969;
background: #d3d3d3;
}
#target {
width: 500px;
height: 100px;
border: 2px solid #000;
margin-left: 10px;
float: left;
border: 2px solid #696969;
background: #d3d3d3;
position: relative;
z-index: 1;
}
#source div,
#target div {
display: block;
padding: 10px;
margin: 20px;
font-weight: bold;
font-family: monospace;
background-color: white;
text-align: center;
max-width: 70px;
border: 5px solid black;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</script>
<div id="source">
<div id="div1" class="div-source">
<select id="selection">
<option>ONE</option>
<option>TWO</option>
<option>THREE</option>
</select>
</div>
</div>
<div id="target" ondrop="drop(event)">
</div>
<div id="inside_drop_zone"></div>
我意识到这篇文章与其他人有重叠,但我很好奇我是否会以最好的方式来解决这个问题,以及是否有任何更好的建议来创建动态选择框。
非常感谢!
【问题讨论】:
-
我强烈建议您不要为此使用 id。您可以使用
document.querySelector("#inside_drop_zone select")之类的方式轻松获取拖放区中的所有选择
标签: javascript jquery jquery-ui jquery-ui-droppable