2011-01-10 86 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);