2016-11-20 138 views
0

让我们考虑下面的情形:更新克隆元素-JQuery

<div class="org"> <p>Some text</p> </div> 

现在使用JQuery:

$vdom = $(".org").clone(); 

现在,我会做一些改变我原来的元素

$(".org p ").text("Changed text");  

如果我执行$vdom.find('p').text()它仍然给“一些文本”。如何根据原始元素发生的变化自动更新克隆元素。

$vdom.find('p').text("changed text"),对于这种情况很好,但是我想自动化这个,原始元素的每一个变化都应该保留在克隆元素中。

是否有任何图书馆来实现这一点。

+0

你可以实现这种从knockout.js事,看看这个小提琴FO一个想法[链接](http://jsfiddle.net/LkqTU/20735/) –

+0

基本上任何MVC/MVVW/MVW框架。看看[TodoMVC](http://todomvc.com/)的例子。 – naeramarth7

回答

0

你必须在clonned元素插入到体内,以它具有对DOM堆栈,然后它可以用一个全球性的选择这样的改变:

$(".org p ").text("Changed text"); 

运行这段代码,并检查两种文本和控制台输出结果:

var $vdom; 
 
    $('#cloneEl').on('click', function() { 
 
    $vdom = $(".org").clone(); 
 
    $('body').append($vdom); 
 
}); 
 

 
$('#changeText').on('click', function() { 
 
    $(".org p ").text("Changed text"); 
 
    console.log($vdom.find('p').text()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="cloneEl">Clone org</button> 
 
<button id="changeText">Change org text</button> 
 

 
<div class="org"> <p>Some text</p> </div>