2010-01-05 64 views
0

IAM使用jQuery的想要做下面书面DOM操作

//this is a template 
    <div class='main'> 
    <div class='header'>Some Text</div> 
    <div class='data'> 
    // data goes here 
    </div> 
    </div> 

// DOM

--------dom here------------- 
<div id='red1' class='red'></div> 
-----more dom (template is here)------------ 

我想是,绑定模板的任何元素(可以说ID = RED1 )得到如下所示的dom

//下面是新的dom

--------dom here------------- 
    <div class='main'> 
    <div class='header'>Some Text</div> 
    <div class='data'> 
// element is wrapped with template 
    <div id='red1' class='red'></div> 
    </div> 
    </div> 
-----more dom (**template is still here**)------------ 

回答

2

喜欢的东西:

// Capture the wrapper template html 
var wrapper = $('<div class="main"><div class="header">Some Text</div><div class="data"></div></div>'); 

// Then replace the "red1" div with the wrapper and since the replaceWith 
// method returns the replaced element, you can just append it right back to your data div 
$('#red1').replaceWith(wrapper).appendTo(wrapper.find('.data')); 
1

jQuery没有内置的模板机制,但有很多JavaScript库提供它。 mustache.js是我喜欢的一种。 Underscore.js,这是对jQuery的很好补充,也有一个简单的模板函数。

1

这听起来像你可以使用wrap函数将该模板封装在带有该ID的div上。