最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I tell jquery to html( ) an element to its original value, before it was dynamically changed? - Stack Overf

programmeradmin2浏览0评论

I have a div, and I used html() to change its content. I am doing a "cancel" button, and I would like to html() back to the original value.

Is there an efficient way to do this? I'm trying to avoid to html() the whole code again, as it doesn't look very good and is probably not the best practice.

Thanks a lot in advance. Regards

I have a div, and I used html() to change its content. I am doing a "cancel" button, and I would like to html() back to the original value.

Is there an efficient way to do this? I'm trying to avoid to html() the whole code again, as it doesn't look very good and is probably not the best practice.

Thanks a lot in advance. Regards

Share Improve this question asked Apr 23, 2012 at 19:29 alexx0186alexx0186 1,5675 gold badges20 silver badges32 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 5
// store the old content
var myOldContent = $("#cancelbutton").html();

// change content
$("#cancelbutton").html(someNewContent);

// and change it back
$("#cancelbutton").html(myOldContent);

If at all possible, don't use .html to toggle content this way -- use two adjacent, nearly-identical elements, one with the old HTML and one with the new, and create a hidden CSS class with display: none and assign it to the second element. Then toggle this hidden class on both elements at the same time.

HTML:

<button class="cancel" id="cancel-original">Cancel</button>
<button class="cancel hidden" id="cancel-second">Cancelling...</button>

CSS:

.hidden {
    display: none;
}

JQuery:

$('button.cancel').click(function() {
    $('button.cancel').toggleClass('hidden'); // toggles both at once
});

http://jsfiddle/e9eLP/

You can clone it when it's made, using jQuery, and when you cancel, delete that and clone the old version back in.

The browser does not track the original value.
However, you can store the original HTML yourself into a variable when the page loads.

You can save the previous HTML content into a variable and then restore from that variable on cancel.

var previousHtml = $('#someElement').html();

Then

$('#someElement').html(previousHtml);

You would need to save it in a variable before changing it:

<script>
var origHTML = $("#divid").html();
function ResetDiv(){
  $("#divid").html(origHTML);
}
</script>

By using jQuery's data() function you can easily hold the original value internally, and then restore it with something like this:

$('#a').click(function(){
    $('div').data('store',$('div').html()).html('foo');
});​​
$('#b').click(function(){
    $('div').html($('div').data('store'));
});
​

jsFiddle example. (Note that this example is just to illustrate how to store a value using data() and not meant for production code.)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论