jQuery 一系列操作后,如何将元素重置为原始状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2944874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reset elements to their original state, after a chain of manipulations?
提问by Moak
After a bunch of animating, adding classes and setting css styles. is there an easy way to reset an element to be back in its original server delivered state?
经过一堆动画,添加类和设置 css 样式。是否有一种简单的方法可以将元素重置为原始服务器交付状态?
回答by user113716
jQuery sets its manipulations using the inline style
attribute, so just set that to ''
.
jQuery 使用 inlinestyle
属性设置其操作,因此只需将其设置为''
.
$('#someDiv').attr('style','');
This assumes there were no inline style
attributes set on the element coming from the server. Better to use style sheets if so.
这假设在style
来自服务器的元素上没有设置内联属性。如果是这样,最好使用样式表。
If the element must come from the server with style
attributes set, then I suppose you could cache the value in a variable, and reset it when needed.
如果元素必须来自style
设置了属性的服务器,那么我想您可以将值缓存在一个变量中,并在需要时重置它。
// Cache original attributes
var originalAttributes = $('#someDiv').attr('style');
// Reset from original
$('#someDiv').attr('style',originalAttributes);
EDIT:
编辑:
If needed, you could send your elements from the server with custom attributes to remember the original class
attribute, for example.
例如,如果需要,您可以从服务器发送带有自定义属性的元素以记住原始class
属性。
<div class="myClass" originalClass="myClass">...</div>
Then you can reference the original anytime you need.
然后您可以随时参考原件。
You could even find all elements that have the originalClass
attribute like this.
您甚至可以找到所有具有originalClass
此类属性的元素。
var $elementsWithOriginal = $('[originalClass]');
or find elements where the class
attribute has been modified from the original.
或查找class
属性已从原始修改的元素。
var $modifiedFromOriginal = $('[originalClass]').filter(function() {
return $(this).attr('class') != $(this).attr('originalClass');
});