2011-01-10 60 views
3

我有以下的HTML代碼mootools的替換div的內容

<div id="myDiv"> 
    <p>content</p> 
</div> 

和下面的JS代碼:

$('myDiv').set('html',htmlCode); 

的問題是,可變htmlCode是一樣的東西:

<div id="myDiv"><p>another content</p></div> 

所以,當我運行JS代碼的結果是這樣的:

<div id="myDiv"> 
    <div id="myDiv"> 
     <p>another content</p> 
    </div> 
</div> 

有沒有使用「設置」的方式,使其覆蓋整個DIV?或另一種解決方案得到類似的東西:

<div id="myDiv"> 
    <p>another content</p> 
</div> 

作爲結果從JS腳本? 我知道我可以更改變量htmlCode ...我只是想知道是否有另一種解決方案。

回答

6

Mootools的提供了一種簡單的方法replaces

//new tmp element that contains the new div 
var tmpDiv = new Element('div',{html:'<div id="myDiv"><p>another content</p></div>'}); 

//new div (first child of my tmp div) replaces the old 'myDiv' (that can be grabbed from the DOM by $) 
tmpDiv.getFirst().replaces($('myDiv')); 
+0

謝謝,它的作品!我投了「實施」的方法作爲接受的答案,但我意識到你的更簡單,而且它在mootools的核心! – 2011-01-16 21:20:24

5
String.implement({ 
    replaces: function(toReplace) { 
     Elements.from(this).inject(toReplace, 'after'); 
     toReplace.destroy(); 
    } 
}); 

'<div id="a"><p>ipsum</p></div>'.replaces($('a')); 

這應該做。例如:http://jsfiddle.net/UvuwG/

+0

感謝!!,它的作品! – 2011-01-16 21:21:38

+4

當然有效!這是MooTools! – 2011-01-17 23:24:51

4
$('myDiv').empty(); 
$('myDiv').adopt(Elements.from(htmlCode).getElement('p')); 
+0

謝謝,它的作品呢! – 2011-01-16 21:20:42

0

你可以做

$("myDiv").getParent().set("html", htmlCode);