jQuery - 将字符从一个列表传输到另一个列表

时间:2012-04-26 20:01:24

标签: jquery foreach each

我有2个字符列表。我正在尝试根据数据属性值使用li和html中的新字符名称更新旧字符列表。单击更改列表时,最终结果如下所示:

//BEFORE
<ul id="new_characters">
<li id="peter"><div data="character1" class="character">Peter Griffin</div></li>
<li id="joe"><div data="character2" class="character">Joe Swanson</div></li>
</ul>

<ul id="old_characters">
<li id="glenn"><span data="character1" class="character">Glenn Quagmire</span></li>
<li id="louis"><span data="character2" class="character">Loius Griffin</span></li>
</ul>

<span id="change">Change List</span>

//AFTER
<ul id="old_characters"> //only this list should change on #change click
<li id="peter"><span data="character1" class="character">Peter Griffin</span></li>
<li id="joe"><span data="character2" class="character">Joe Swanson</span></li>
</ul>

这是一个小提琴:http://jsfiddle.net/wXnSZ/

2 个答案:

答案 0 :(得分:2)

$('#change').click(function(){
    $('.character', '#new_characters').each(function(index, item){
        $(".character[data='"+$(item).attr('data')+"']", "#old_characters").text($(item).text());
    });    
});​

FIDDLE

要替换ID,但要保持跨度:

$('#change').click(function(){
    $('.character', '#new_characters').each(function(index, item){
        $(".character[data='"+$(item).attr('data')+"']", "#old_characters").text($(item).text()).parent().attr('id', $(item).parent().attr('id'));
    });    
});​

FIDDLE

或根据数据属性更改old_characters中每个li的完整html:

$('#change').click(function(){
    $('.character', '#new_characters').each(function(index, item){
        $(".character[data='"+$(item).attr('data')+"']", "#old_characters").replaceWith($(item).clone());
    });    
});​

FIDDLE

或者只是将new_characters的HTML放入old_characters:

$('#change').click(function(){
   $("#old_characters").html($('#new_characters').html());
});​

FIDDLE

答案 1 :(得分:0)

以下是两种可能性:

1)在旧字符列表中添加新字符:

$('#change').click(function() {
    $('#old_characters').append($('#new_characters').contents());
    $('#new_characters').remove();
});​

2)用新字符替换旧字符:

$('#change').click(function() {
    $('#old_characters').contents().replaceWith($('#new_characters').contents());
});​
对于解决方案#2,

jsFiddle example