2013-07-16 38 views
0

我有下面的HTML。刪除時重新分配多個ID

<ul> 
    <li id="myli-1"> 
     <input id="name-1" /> 
     <input id="surname-1" /> 
     <span class="remove">X</span> 
    </li> 
    <li id="myli-2"> 
     <input id="name-2" /> 
     <input id="surname-2" /> 
     <span class="remove">X</span> 
    </li> 
    <li id="myli-3"> 
     <input id="name-3" /> 
     <input id="surname-3" /> 
     <span class="remove">X</span> 
    </li> 
    <li id="myli-4"> 
     <input id="name-4" /> 
     <input id="surname-4" /> 
     <span class="remove">X</span> 
    </li>  
</ul> 

用戶與點擊刪除第二項目第二X

$(".remove").live('click', function() { 
     $(this).parent().remove(); 
}); 

我怎樣才能讓ID S的以下項目myli-3, name-3, surname-3, myli-4等可以降低1?

我創造了這個JSFiddle

+2

你需要在動態列表中使用的ID這樣嗎?刪除ID並避免棘手的重新分配可能會更聰明。相反,一旦你準備好和他們一起做點什麼,你可以用jQuery抓住他們(如果需要的話,可以指定他們的指數)。 –

+0

你的小提琴不起作用,因爲'.live()'在你選擇的jQuery版本中不可用。這是一個更新的版本:http://jsfiddle.net/QZcY5/3/ – nnnnnn

+0

使用這個你的點擊功能:'$(「body」)。on('click',「.remove」,function(){$(這個).parent()。remove();});' – Johannes

回答

0

你可以嘗試創建一個自定義過濾器的jQuery。順便說.live()是因爲1.7

Fiddle

棄用嘗試

$(".remove").click(function() 
{ 
     $(this).parent().remove(); 
     refreshIndex(); 
}); 

function refreshIndex() 
{ 
    $('ul li').filter(hasIdWithIndex).each(updateIdWithIndex); 
    $('ul li input').filter(hasIdWithIndex).each(updateIdWithIndex); 

    function hasIdWithIndex() 
    { 
    return this.id.search(/\d$/) != -1; 
    } 

    function updateIdWithIndex() 
    { 
     var $this = $(this); 
     var id  = this.id; 
     var index = $this.closest('li').index(); 

     id   = this.id.substring(0, id.length -1); 
     this.id  = id + index; 
    } 

} 
+0

爲了保持「實時」功能,您應該將它用於點擊邏輯:'$(「body」)。on('點擊','.remove',function(){$(this).parent()。remove();});'這樣你就可以避免需要解除/重新綁定新的插入。 – Johannes

+0

我同意但我會使用$(「ul」),我喜歡儘量縮小範圍。 –