2013-03-11 63 views
2

我正在使用jQuery UI的拖放功能,並在'放下'它將項目添加到<ul>元素與','後每個項目。對於最後需要的<li>我該如何動態刪除逗號並在該項之前添加單詞and如何動態刪除逗號並添加單詞並使用jQuery

我想:

$(#pot ul li:last-child).text().replace(/,/g, '');

但是,這給了我沒有運氣。

$(function() { 
    $(".flavours li").draggable({ 
     revert:true 
    }); 

    $("#pot ul").droppable({ 
     activeClass: "ui-state-default", 
     hoverClass: "ui-state-hover", 
     drop: function(event, ui, flavours) { 
      $("<li></li>").text(ui.draggable.text() + ',').appendTo(this); 
     } 
    }) 
}); 

回答

2

爲了單獨的內容和表現,你可以這樣做在純CSS中,如果您不需要與IE8兼容:

#pot ul li:not(:last-child):after { 
    content:","; 
} 

Demonstration

更兼容的,你也可以做到這一點之後使用jQuery和相同的選擇:

$('ul li:not(:last-child)').append(','); 

,或者你可以定義使用jQuery類:

$('ul li').each(function(){ // this can be called each time you change the list 
    if ($(this).is(':last-child')) { 
    $(this).removeClass('notLast'); 
    } else { 
    $(this).addClass('notLast'); 
    } 
}); 

Demonstration

+1

優秀的答案,@dystroy你簡直令人驚歎。 – Adil 2013-03-11 17:45:52

+0

@Adil感謝您的誇獎。來自像你這樣的經驗豐富的用戶,非常感謝。 – 2013-03-11 17:47:23

2

括在quotes選擇,你必須修改文本分配回到單元

$('#pot ul li:last-child').text($('#pot ul li:last-child').text().replace(/,/g, '')); 

el = $('#pot ul li:last-child'); 
el.text(el.text().replace(/,/g, 'and')); 
+0

唯一的問題是,當我在drop上進行操作時,它假定每個元素都是th最後一個,即使我添加新的。我需要做的還是告訴它其他元素不是最後一個孩子。因爲,隨着元素被逐個添加,每個元素都是最後一個孩子。 – 2013-03-11 17:37:16

+1

哪裏用'和'代替最後的逗號? – Archer 2013-03-11 17:44:30

相關問題