简体   繁体   English

如何删除jquery添加的元素?

[英]How can I remove an element added by jquery?

I want list items moved to a div when clicked and vice versa. 我希望单击时将列表项移至div,反之亦然。 But it seems, only elements loaded from the source can be moved. 但似乎只有从源加载的元素可以移动。

How can I do that? 我怎样才能做到这一点? Thanks. 谢谢。

 <div class="green">
    <ul id="selectable">
        <li class="content-item">Item A</li>
    </ul>
</div>


<div class="red">
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
</div>

<script>

$(".selected-item").click(function() {
    var text =  "<li class='content-item' >"+$(this).text()+"</li>";
    $(".green #selectable").prepend( text );
    $(this).remove();
});

$(".content-item").click(function() {
    var text =  "<span class='selected-item'>"+$(this).text()+"</span>";
    $(".red").append( text );
    $(this).remove();
});
</script>

http://jsfiddle.net/wGz8s/112/ http://jsfiddle.net/wGz8s/112/

Try to use event delegation here since the elements that you are adding at the runtime would not be available during event binding, 请尝试在此处使用event delegation ,因为您在运行时添加的元素在事件绑定期间将不可用,

$(document).on("click",".selected-item", function() {
   var text =  "<li class='content-item' >"+$(this).text()+"</li>";
   $(".green #selectable").prepend( text );
   $(this).remove();
});

and

$(document).on("click",".content-item", function() {
  var text =  "<span class='selected-item'>"+$(this).text()+"</span>";
  $(".red").append( text );
  $(this).remove();
});

And in the place of the document in my code use a static closest dom element of the selector which is being passed inside .on() 并在我的代码中的文档位置使用选择器的静态最接近dom元素,该元素在.on()内部传递

You should use jQuery's event delegation . 您应该使用jQuery的事件委托

The problem is: your jsFiddle is using jQuery 1.4 (very old version), and it doesn't have the .on event. 问题是:您的jsFiddle使用的是jQuery 1.4(非常旧的版本),并且没有.on事件。

I've updated it to the version 1.11, and it works like a charm: 我已经将其更新为版本1.11,它的工作原理很像:

$(".abc").on("click", "span", function(e) {
    var text =  "<li class='content-item' >"+$(e.target).text()+"</li>";
    $(".choices #selectable").prepend( text );
    $(e.target).remove();
});

$(".choices").on("click", "li", function(e) {
    var text =  "<span class='selected-item'>"+$(e.target).text()+"</span>";
    $(".abc").append( text );
    $(e.target).remove();
});

http://jsfiddle.net/wGz8s/113/ http://jsfiddle.net/wGz8s/113/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM