How can I “reset”
to its original state afte

2020-01-24 03:43发布

I have a DIV with a form in it. When users submit the form and it gets successfully submitted, I replace the form with a simple "everything is good now" message:

$("#some_div").html("Yeah all good mate!");

Is there a good way to "reset" the div to its "original state" as per the HTML it has arrived with? I can only think of actually doing something like this:

//before I change the DIV
var originalState = $("#some_div").html();
//manipulate the DIV
//...
//push the state back
$("#some_div").html(originalState);

It doesn't look very elegant - I guess there is a better solution for this, no?

10条回答
够拽才男人
2楼-- · 2020-01-24 04:17

What you're doing is not optimal. The best solution would be this:

When the form gets successfully submitted, just hide() the FORM element, and show() the message (which is initially hidden). And then, later, just show() the FORM element and hide() the message.

查看更多
smile是对你的礼貌
3楼-- · 2020-01-24 04:24

You have basically three options.

  1. Remember your original markup, as you do with your originalState variable above.
  2. Use AJAX to re-request the markup. You can do this easily if you have server side code using the $.ajax() method in jQuery.
  3. Cause the page to reload.
查看更多
爷的心禁止访问
4楼-- · 2020-01-24 04:25

You can use the data attribute to save the state rather than a variable

$('#some_div').data('old-state', $('#some_div').html());
$('#some_div').html($('#some_div').data('old-state'));
查看更多
Juvenile、少年°
5楼-- · 2020-01-24 04:30

var originalState = $("#some_div").clone(true, true); $("#some_div").replaceWith(originalState.clone(true, true));

查看更多
Evening l夕情丶
6楼-- · 2020-01-24 04:31

In my opinion best is to use this:

var originalState = $("#some_div").clone();
$("#some_div").replaceWith(originalState.clone());

This way you can repeatedly use this to restore your div to original state while keeping the data in "originalState" intact. Worked for me.

查看更多
家丑人穷心不美
7楼-- · 2020-01-24 04:33

Yeah, the way you have is the way to do it. The DOM does not save the previous states of DIVs, so you need to save that yourself.

查看更多
登录 后发表回答