如何动态删除 div 并清除内存,以便我可以使用 jQuery 添加具有相同 ID 但不同内容的新 div?
我正在使用 Picasa Web Integrator (PWI) 代码,它允许我使用 picasa 帐户展示图片库。用户使用表单编写一个关键字,然后用代码创建一个 div 并调用 PWI。
它工作得很好,但我试图添加一个“后退”按钮,以便让用户选择不同的关键字而无需刷新。
但代码似乎没有清除内存,结果与第一次相同。
这是代码:
//The button that the user presses when he has written the keyword.
$("#boton2").click(function() {
//Creates a new div
$(".shop3").append("<div></div>");
$('.shop3 > div').attr('id', 'container3');
//gets the keyword and creates a variable called "competidor"
competidor = $('#competidor_txt').val();
//calls for the PWI code...
$("#container3").pwi({
username: 'davidagnino',
mode: 'keyword',
...
//This part works perfectly.
//The "back" button that should delete the div called #container3
$('#back3').click(function() {
event.preventDefault();
competidor=null;
delete competidor;
$("#container3").empty(); //should make my div empty
$("#container3").remove(); //deletes the div...
});
I am using the Picasa Web Integrator (PWI) code, that allows me to present a picture gallery using a picasa account. Using a form the user writes a keyword and then a code creates a div and calls for the PWI.
It works perfectly, but I'm trying to add a "back" button in order to let the user select a different keyword without refreshing.
But the code doesn't seem to clear the memory and the result is the same as the first time.
Here is the code:
//The button that the user presses when he has written the keyword.
$("#boton2").click(function() {
//Creates a new div
$(".shop3").append("<div></div>");
$('.shop3 > div').attr('id', 'container3');
//gets the keyword and creates a variable called "competidor"
competidor = $('#competidor_txt').val();
//calls for the PWI code...
$("#container3").pwi({
username: 'davidagnino',
mode: 'keyword',
...
//This part works perfectly.
//The "back" button that should delete the div called #container3
$('#back3').click(function() {
event.preventDefault();
competidor=null;
delete competidor;
$("#container3").empty(); //should make my div empty
$("#container3").remove(); //deletes the div...
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为最好的方法是动态更改 Div 的 ID,从而每次将其设置为一个全新的 div。
我会设置一个计数器变量(理想情况下是静态的,但如果您无法理解,则为全局变量):
当需要销毁该变量时,增加 divCounter 并生成一个全新的 div。应该完成任务!
显然,在所有事件处理程序中,您都会通用地引用它:
快速说明,删除某些内容会将其从 DOM 中完全删除,从而在同一操作中将其清空。将函数链接在一起也是很好的 jQuery 实践,如下所示:
I think the best approach here would be to change the Div's ID on the fly, and thus set it up as a whole new div each time.
I'd set up a counter variable (ideally static, but global if that's over your head):
when it's time to destroy that, increment divCounter and generate a whole new div. Should get the job done!
Obviously, in all your event handlers you'd refer to it generically:
A quick note, removing something completely removes it from the DOM, thus emptying it in the same operation. It's also good jQuery practice to chain your functions together, like this: