[英]javascript / jquery - get and hold element's initial html content
這可能是非常基本的,但是我正在拖延...
在頁面加載時,我需要將元素的html內容保存到變量中。 頁面中還有其他代碼,這些代碼將更改元素的html內容。 因此,我需要能夠將值恢復為默認值(頁面加載時的值)。 問題是我的變量值被更改為最新值。
如何使分配給變量“ stick”的初始值?
currentElementsHTML = $("#myDOMElement"),
currentElementsHTMLDefaultValue = currentElementsHTML.html()
... do stuff that changes currentElementsHTML
... revert to currentElementsHTMLDefaultValue whenever i need to
您可以通過多種方式存儲一些數據並在以后提供這些數據,其中一些方法需要了解JavaScript范圍的工作方式,而其他方法則僅依賴jQuery方法。
這樣做的不好方法是將值存儲為全局變量:
function at_the_start(){
/// notice there is no var keyword, this means the variable will be global
global_html = $('element').html();
}
function later_on(){
$('element').html( global_html );
}
您不應該這樣做,因為您的數據會“污染全局名稱空間”-基本上,這意味着其他代碼可以輕松訪問您的變量(並弄亂它) ,並且您可能會無意中覆蓋其他一些代碼的全局數據-尤其是當您使用通用名稱時。
更好的方法是為自己的目的使用JavaScript的功能,即它的作用域能力,這里有一些優點可供閱讀-JavaScript中變量的作用域是什么? :
function my_code(){
var html = $('element').html();
/* Do stuff here */
$('element').html( html );
}
上面的內容依賴於局部變量,而且您必須將所有內容都保留在同一函數調用中。 由於很可能您將依賴於用戶觸發的事件的混合,因此您不能真正使用以上內容。 這是因為您將在不同的位置使用許多函數,並且它們不能共享相同的局部變量。 還是可以?
以下是我所謂的“全局局部”變量-完全有可能不是它的真實名稱,但是它描述了我看到的東西:
function my_code(){
/// this variable is local, due to the var keyword
/// but it will be accessible in both the functions below
var html_local = '';
var my_function_to_start = function(){
html_local = $('element').html();
}
var after_other_things_have_happened = function(){
$('element').html( html_local );
}
/// you can even apply these functions to say an event handler
/// and the variable will be remembered because it exists within
/// the "after_other_things_have_happened" function's scope.
$('another.element').click(after_other_things_have_happened);
}
上面的方法起作用是因為JavaScript函數始終可以訪問在先前的父塊/父作用域或父函數中定義的變量。
考慮到您使用的是jQuery,jQuery提供了一種非常簡單的方法來存儲任意數據,並且您無需了解有關范圍或本地和全局var的任何知識。 我花了一段時間寫這篇文章,所以很明顯,這一次其他海報者已經正確地指出以下內容是個好主意-jQuery Data :
$('element').data( 'old_html', $('element').html() );
然后,可以使用以下任何時間對其進行訪問:
$('element').data( 'old_html' );
所以...
$('element').html( $('element').data( 'old_html' ) );
將把值放回去-該值與元素一起存儲,因此無論您何時訪問$('element')
,都可以獲取分配給它的數據。
有時,另一個有用的功能是JavaScript將幾乎所有數據類型都視為一個對象。 這意味着您可以將屬性添加到幾乎所有內容。 如果有些奇怪,以下實際上是可能的。
var a = new String('This is a string');
a.withAProperty = 'another string';
alert(a);
alert(a.withAProperty);
我有時會使用它在函數上創建偽靜態屬性,如下所示:
var my_function = function(){
if ( ! my_function.staticProp ) {
my_function.staticProp = 'abc';
}
/* use my_function.staticProp for something here */
}
var another_function(){
/* you can also access my_function.staticProp here
but only after my_function has been called once */
}
/* and my_function.staticProp here, but only
after my_function has been called once */
這幾乎與使用全局var具有相同的效果(特別是如果將其應用於全局函數),但意味着您的值存儲在函數名稱空間的頂部,從而大大降低了與其他代碼發生沖突的可能性。 這確實仍然意味着外部代碼可以影響var的內容-實際上,根據您要執行的操作,這可能是一個好處。
根據您希望存儲的內容,有時在DOM中記錄該數據可能會有所幫助。 其中最明顯的是將數據寫入隱藏的輸入或隱藏的元素中。 后者的好處是,如果它恰好采用標記信息的形式(如您的那樣) ,您仍然可以導航此數據(使用jQuery或document.getElementById之類的 東西) 。 這也可以是避免循環引用導致的內存泄漏的有益方法(如果您要處理大量數據),只要確保清空與數據傳輸有關的變量即可。
$.ajax('request_html.php').done(function(data){
$('<div id="hidden_html" />').hide().html(data).appendTo('body');
data = null;
/// you only need mullify data if you were to have other
/// sub/child functions within this callback, mainly being wary
/// of closures - which are functions that are defined in a certain
/// scope chain, but are then returned or put to use outside of
/// that chain - i.e. like event listeners.
/// nullify vars and removing large properties is still good practice though.
});
然后,當您要檢索時:
$('#hidden_html').html();
同時,在這兩點之間,您顯然仍然可以遍歷數據:
$('#hidden_html h1 > a[name=first]');
您將原始HTML與相同的DOM元素相關聯,這樣它就不會消失:
$("#myDOMElement").data("initial-html", $("#myDomElement").html());
類似的東西,但尚未測試:
$(function() {
$('#id').data('store', $('#id').html());
});
...
$('#id').html(data('store'));
如果將.html()
的內容壓入一個變量,它將保留在那里,除非您對該變量進行某些操作以將其刪除:
var original = $("#foo").html(); // original HTML is now in 'origina'
除非您進行更改,否則它不會更改。
不過,對您來說,將其作為數據(使用jQuery的.data
方法)存儲在元素本身上可能更為有利:
var element = $("#foo");
element.data( "original", element.html() );
這樣,您隨時可以在以后訪問它:
console.log( element.data( "original" ) );
記錄,重置和還原演示: http : //jsfiddle.net/ft8M9/
// Access all elements to restore
var restore = $(".restore");
// Save original HTML, and set new HTML
restore.each(function(i,o){
var that = $(this);
that.data("original", that.html())
.html("Changed " + i);
});
// After 2 seconds, restore original HTML, remove stored data
setTimeout(function(){
restore.each(function(i,o){
var that = $(this);
that.html( that.data("original") )
.removeData( "original" );
});
}, 2000);
演示: http : //jsfiddle.net/ft8M9/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.