JQuery 添加元素,包括删除侦听器
添加元素(包括元素)的最佳方式是什么?一个删除自身的链接,到一个div? 这几乎有效:
function displayElements(objekt) {
$('#container').empty();
for(var key in objekt) {
if(objekt.hasOwnProperty(key)) {
$('#container').append('<div id="' + key + '">' +
key +
'<a id="del' + key + '">delete'</a></div>');
$('#del' + key).click(function() {
delete objekt[key];
displayElements(objekt);
});
}
}
}
奇怪的效果是,无论我单击哪个删除链接,最后一个元素总是被删除。 为什么会这样?有没有更优雅的方法来实现这一点?
问候,埃里克
What is the best way to add elements, incl. a link to remove themselves, to a div?
This almost works:
function displayElements(objekt) {
$('#container').empty();
for(var key in objekt) {
if(objekt.hasOwnProperty(key)) {
$('#container').append('<div id="' + key + '">' +
key +
'<a id="del' + key + '">delete'</a></div>');
$('#del' + key).click(function() {
delete objekt[key];
displayElements(objekt);
});
}
}
}
The strange effect is, that no matter which delete link I click, always the last element gets deleted.
Why is that and is there a more elegant way to accomplish this?
Regards, Eriq
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将其替换为:
You can replace that with:
我会将事件内容移出循环:
I'd move the event stuff out of the loop: