2013-01-21 57 views
0

在用戶按下div中的鍵後,html被設置爲「」。但是,在用戶離開div後,我想將html設置回它的原始值。我怎樣才能做到這一點?如何將html內容恢復爲原始值?

我有下面的代碼至今:

$(document).one('keypress',"#id",function() { 
     $(this).html(""); 
    }).focusout(function(){ 
     //do something 
    }); 

回答

6

緩存它在元素本身:

$(document).one('keypress',"#id",function() { 
    $(this).data('html',$(this).html()).html(''); 
}).focusout(function(){ 
    $(this).html($(this).data('html')); 
}); 

我喜歡這個因爲通過將數據存儲在this上,它可以與任何選擇器協同工作包括匹配多個DOM元素的那些。您只需確保data()變量('html'此處)未被頁面上的任何其他代碼使用。

2

也許是這樣的:使用.data()

var orig; 
$(document).one('keypress',"#id",function() { 
     orig = $(this).html(); 
     $(this).html(""); 
    }).focusout(function(){ 
     //do something 
     $(this).html(orig); 
    }); 
0

您需要將值存儲在變量中,以便在焦點轉出後可以將其恢復。

var divValue; 
$(document).one('keypress',"#id",function() { 
    divValue = $(this).html(); 
    $(this).html(""); 
}).focusout(function(){ 
    $(this).html(divValue); 
}); 
3

如何:

(function() 
{ 
    var html = null; 
    $(document).one('keypress',"#id",function() { 
     html = $(this).html(); 
     $(this).html(""); 
    }).focusout(function(){ 
     //do something 
     $(this).html(html); 
    }); 
})(); 

我把它包在一個自執行的匿名功能,使您保持html變出來的主要範圍。

或者更jQuery的方式:

$(document).one('keypress',"#id",function() { 
    $(this).data('orightml', $(this).html()); 
    $(this).html(""); 
}).focusout(function(){ 
    //do something 
    $(this).html($(this).data('orightml')); 
}); 

這樣我們存儲對元素原始的HTML。

相關問題