简体   繁体   English

jQuery无法在.appended内容中工作

[英]jquery not working in .appended content

I have a div, which has content populated on load (a bunch of 'span' tags with a delete link in each. clicking the delete button will remove that span. Now you can also add new 'span' tags to it using a separate button (each with their own delete button). The initially loaded span delete buttons work fine, but the newly added ones do not delete. 我有一个div,它的内容已加载(每个“ span”标签中都有删除链接)。单击“删除”按钮将删除该范围。现在,您也可以使用单独的标签向其中添加新的“ span”标签按钮(每个按钮都有自己的删除按钮)最初加载的跨度删除按钮可以正常工作,但新添加的按钮不会删除。

<div class="instances"> 
<span class="item">Instance 1 <a href="#" class="del">delete</a></span>
<span class="item">Instance 2 <a href="#" class="del">delete</a></span>
</div>
<span class="addinstance">Add an instance</span>


$('.addinstance').click(function () {
$('.instances').append('<span class="item">More <a href="#" class="del">delete</a></span> ');
});

$('.instances .del').click(function (event) {
event.preventDefault();
$(this).parent('.item').hide();
});

Check out the fiddle I made for a working version of this: http://jsfiddle.net/Ac7x6/3/ 查看我为该版本制作的小提琴: http : //jsfiddle.net/Ac7x6/3/

In the fiddle: 在小提琴中:

  1. Click the delete button on Instance 1 - works fine. 单击实例1上的删除按钮-运行正常。

  2. Click the 'Add an Instance' button - this adds an new entry. 点击“添加实例”按钮-这将添加一个新条目。

  3. Click the 'delete' button on the newly added instance - does not delete. 单击新添加的实例上的“删除”按钮-不删除。

I have read a lot about this issue, including jquery .on(). 我已经读过很多关于这个问题的文章,包括jquery .on()。 Just not sure exactly how to implement them. 只是不确定确切如何实现它们。

Help! 救命! :) :)

Use event delegation for dynamically generated items, If you wanna remove the item then use remove() 将事件委托用于动态生成的项目,如果要删除项目,请使用remove()

$('.instances').on('click','.del',function (event) {
    event.preventDefault();
    $(this).parent('.item').remove();
});

Fiddle Demo 小提琴演示

try this, 尝试这个,

$(document).on("click", '.instances .del', function (event) {
    //your code
});

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

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