删除使用 JQuery 动态添加的 html 元素
在我的 html 页面中,我有一个带有一些选项的选择。
选择选项时,会触发 ajax 调用,将该选项的值传递给 php 脚本,该脚本返回带有附加到页面的特定 id 的 html 片段(另一个选择)。
当用户从第一个选择中选择另一个选项时,该事件将再次触发,执行 ajax 调用,并将另一个 html 片段(具有相同的 id)附加到页面。
我希望,如果第二次触发该事件,则在附加新元素之前将从页面中删除附加元素。
目前我正在使用这段代码:
$(document).ready(function() {
$("#id_serie").change(function() { //#id_serie is the if of the first select
if ($("#id_subserie_label")) { //#id_subserie_label is the id of the html element returned by the ajax call
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
但这不起作用,第二个ajax调用返回的html元素附加在第一次调用返回的元素之后(因为当脚本已加载?)。
我怎样才能实现我所需要的?
In my html page, I have a select with some options.
When selecting an option, an ajax call is fired passing the option's value to a php script, which returns an html fragment (another select) with a certain id that is appended to the page.
When the user selects another option from the first select, the event is fired again, the ajax call is executed and another html fragment (with the same id) gets appended to the page.
I want that, if the event is fired a second time, the appended element is removed form the page before appending the new one.
At the moment I'm using this code:
$(document).ready(function() {
$("#id_serie").change(function() { //#id_serie is the if of the first select
if ($("#id_subserie_label")) { //#id_subserie_label is the id of the html element returned by the ajax call
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
This is not working though, the html element returned by the second ajax call is appended after the element returned from the first call (because the element with id #id_subserie_label is not in the page when the script is loaded?).
How can I achieve what I need?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经非常接近了。
只需将
if ($("#id_subserie_label"))
更改为if ($("#id_subserie_label").length)
code>:请参阅 jQuery 常见问题解答:如何测试元素是否存在?。
这是因为,正如 Ivo 指出的那样:
根据 Andy E 的 评论,如果您不需要
,您可以将代码简化为此console.log() 调用:
You're very close.
Just change
if ($("#id_subserie_label"))
toif ($("#id_subserie_label").length)
:See The jQuery FAQ: How do I test whether an element exists?.
This is because, as Ivo points out:
As per Andy E's comment, you can simplify your code to this, if you don't need the
console.log()
call: