jQuery undo click()函数更改

时间:2013-11-23 15:36:41

标签: jquery click

我想在表单输入文本字段上对css和类进行一些更改,当用户单击“回复”按钮并使其正常工作时,然后底部的表单会保留更改。 所以我的问题是:有没有办法撤消这些更改并将表单返回到以前的状态?

$(".comment-reply-link").click(function() {
    if($("#commentform").width() < 590){
        $("#commentform input[type='text']").css("margin-left","0");
        $("#commentform input[type='text']").removeAttr('class');
    }
})

3 个答案:

答案 0 :(得分:2)

AFAIK,没有方法可以存储DOM中发生的更改并在需要时还原。您可以像下面那样实现

 $('.element').bind('click', plus10);
 $('.revertChange').bind('click', minus10);
 var input = $('#someInput');

 function plus10(){ 
      input.val(input.val() * 1 + 10); 
 }
 function minus10(){ 
      input.val(input.val() * 1 - 10); 
 }

如果您正在尝试添加样式并恢复创建具有必要样式的类,则切换类

 .someClass{
      margin:10px;
      color:green;
      /* ...... */
 }

然后在下面的元素上切换类

 $('element').toggleClass( "someClass" );

答案 1 :(得分:0)

如果您要撤消内联样式,那么您可以:

$("#commentform input[type='text']").css("margin-left","");

这将重置/撤消您的内联样式margin-left

答案 2 :(得分:0)

这是一种使用jquery的数据存储克隆状态并随时恢复的方法。无论您对元素所做的更改数量如何。 例如,

http://jsfiddle.net/xr63r/

<强> HTML

<div id="commentform">
    <input type="text" class="red-border" />
    <button class="comment-reply-link">test</button>
</div>
<button class="undo">undo</button>

<强> JS

$(".comment-reply-link").click(function() {
    if($("#commentform").width() < 590){
        /*create a clone of the element you modify*/
        var theClone = $("#commentform").clone(true,true);
        /*add the cloned element to a data attribute for restoring the state*/
        $("#commentform").data("undo",theClone);

        /*any kind of css modifications may follow*/
        $("#commentform input[type='text']").css("margin-left","0");
        $("#commentform input[type='text']").removeAttr('class');
    }
})

$(".undo").click(function(){
/*if state undo exists, restore it*/
    if($("#commentform").data("undo")){
        var theClone = $("#commentform").data("undo");
        $("#commentform").replaceWith(theClone);
    }
});

<强> CSS

/*this is an example css style related to a class*/
input.red-border{
    border:red 1px solid;
}