我正在开发一个小部件,在汽车行业被称为压扁的 Frog 。它基本上是一辆被压扁的汽车的图像,带有显示损坏位置的图标。我有一个 HTML 图像图标列表,当用户单击时我希望复制这些图标,因此该 HTML 图标的副本将放置在容器 div 中,然后可以将其拖动到汽车图像上的位置损坏已定位。
创建副本并且是父容器 div 的子级后,我想添加类 "draggable" 以便可以拖动它,然后删除类 "frog-key”,因此在单击时不会创建此副本的另一个副本。
问题是一旦单击元素,我就很难删除“frog-key”类...
这是我的代码...
<!-- Script -->
<script type="text/javascript">
$(function () {
$(".draggable").draggable();
});
$(document).ready(function () {
// when an element is clicked, a duplicate is created that can be dragged.
// where it is placed is where the coordinates will be saved
$(".frog-key").click(function () {
var copy = $(this).clone(true);
// add a unique ID
copy.attr("id", copy.attr("data-type") + "-1");
// remove class frog-key as we dont want a duplicate of this copy
copy.removeClass("frog-key");
// add the class draggable - so it can be dragged - jquery UI
copy.addClass("draggable");
// add this copy to the container div
$("#squashed-frog-container").append(copy);
});
})
</script>
HTML
<div id="squashed-frog" class="large">
<div id="squashed-frog-container">
<img id="squashed-frog-art" src="/Content/Design/img/ART_squashed_frog_large.png">
</div>
<ul class="unstyled" id="squashed-frog-key">
<li><span class="pointer sprite frog-key dent" data-type="Dent_Bodyshop"></span>Dent <small>(Bodyshop)</small></li>
<li><span class="pointer sprite frog-key dent-repair" data-type="Dent_SmartRepair"></span>Dent <small>(Smart Repair)</small></li>
<li><span class="pointer sprite frog-key scratch" data-type="Scratch_Bodyshop"></span>Scratch <small>(Bodyshop)</small></li>
<li><span class="pointer sprite frog-key scratch-repair" data-type="Scratch_SmartRepair"></span>Scratch <small>(Smart Repair)</small></li>
<li><span class="pointer sprite frog-key chip" data-type="Scratch_Chip"></span>Chip</li>
<li><span class="pointer sprite frog-key multi-chip" data-type="Multiple_Chips"></span>Multiple Chips</li>
<li><span class="pointer sprite frog-key paint" data-type="Paint_OffColour"></span>Paint <small>(Off Colour)</small></li>
<li><span class="pointer sprite frog-key paint-repair" data-type="Paint_PreviousRepair"></span>Paint <small>(Previous Repair)</small></li>
<li><span class="pointer sprite frog-key paint-fallout" data-type="Paint_Fallout"></span>Paint <small>(Fallout)</small></li>
<li><span class="pointer sprite frog-key rust" data-type="Rust"></span>Rust</li>
<li><span class="pointer sprite frog-key wheel-Scuff" data-type="Wheel_Scuff"></span>Wheel Scuff</li>
<li><span class="pointer sprite frog-key sidewall" data-type="Sidewall_Damage"></span>Sidewall Damage</li>
<li><span class="pointer sprite frog-key broken" data-type="Broken"></span>Broken</li>
</ul>
最佳答案
您只是缺少一行(加上我必须在点击事件中重新初始化可拖动 - 但这可能是 fiddle 的错误):
copy.unbind("click");
$(".draggable").draggable();
当您克隆该元素时,它保留了它的单击事件。 .frog-key 实际上已按计划删除,但并非每次都进行评估;一旦页面加载,事件就会附加到元素及其克隆,并保持这种状态,直到专门解除绑定(bind)。
我希望这会有所帮助。
关于Jquery UI - 创建重复的 DOM 元素,然后添加和删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15906727/