为拖放区中的选择创建唯一的ID

问题描述 投票:0回答:1

我意识到这个问题与其他发布的问题类似,但是我希望有人可以帮助我解决这个问题:

我在使用JQuery拖放的可拖放项中有一个select元素,该元素在拖动时被克隆。元素具有ID select,但我需要ID是唯一的,以便可以在放置区域中的每个框访问不同的所选选项。

enter image description here

在拖放区域下方,您会看到选择框ID,只要拖动新块,我的期望输出便是select_1select_2select_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>

[我知道这篇文章与其他文章有重叠之处,但是我很好奇我是否正在寻求最好的方法,是否有创建动态选择框的更好建议。

非常感谢!

[我意识到这个问题与其他发布的问题类似,但是我希望有人可以帮助我解决这个问题:我在使用JQuery拖放的可放置项中有一个select元素,它是...

javascript jquery jquery-ui jquery-ui-droppable
1个回答
0
投票

如果您真的需要它们具有唯一的ID,则完全放弃默认ID,然后通过类似以下操作添加它们:

© www.soinside.com 2019 - 2024. All rights reserved.