2011-10-28 42 views
2
var el = $(this); // it's a form 

在某一點上:jQuery replaceWith不保留鏈接到DOM中的元素?

el.replaceWith('<p>Loading...</p>'); 

後來:

el.replaceWith(output); 

顯然EL不第一replaceWith後不復存在......

我能留下莫名其妙el,顯然與新的內容?

+0

你可以使用'的.html()'更換元件內部無需更換元素本身。 – Blazemonger

回答

3

原始el已被刪除並替換爲replaceWith。創建一個新的參考,使用replaceWith返回值:

var el = $(this); // it's a form 
el = el.replaceWith('<p>Loading...</p>'); 
       //`el.replaceWith()` returns the new element 
el = el.replaceWith(output); 

如果您打算更換新的元素內的內容,同時保持形狀,用途:

el.html(""); //Clear html 
el.append('<p>Loading...</p>'); 
+0

謝謝,我發現replaceAll做我想要的:'el = $('

loading ...

').replaceAll(el);' – Alex

+1

replaceWith似乎返回被刪除的元素,而不是新的元素,檢查:http://api.jquery.com/replaceWith/ – opensas

+0

也檢查這個問題在SO http://stackoverflow.com/questions/892861/replacing-an-element-and-returning-the-new-one -in-的jQuery – opensas

1

jQuery的replaceWith返回替換元素,而不是新的

http://api.jquery.com/replaceAll/

你應該做這樣的事情:

var el = $(this); // it's a form 
var $p = $('<p>Loading...</p>'); 

el.replaceWith($p); 

// now el is unhooked from the dom, that is el.parent() === [] 
// it is $p who is now hooked, check with $p.parent() === (some node) 

//so you should reassing it 
el = $p; 

// later on 

el.replaceWith(output); // but remenber, once again el is unhooked 

也,一定要檢查這個問題:https://stackoverflow.com/a/892915/47633

相關問題