2015-07-19 67 views
1

现在,当您添加它们被编号为1 1输入之后让我们说我们加5米的冠军,他们将被编号喜欢删除中间投入重新编号数据-ID

而且我们说,我们要删除第3一个它的Wi会像

而且我想我要取出后像

    编号

这里是一个工作http://jsfiddle.net/dyje773m/http://89.69.172.125/cms2.0/

代码的最重要的部分:

$(document).ready(function(){ 
    championNumberArray = 0; 
    championNumber = 1; 
    $('a#AddChampion').on('click',function(){ 
     $('div#ChampionInput').append(
     '<div class="Champion" data-id="'+championNumberArray+'">\ 
      <a href="#" class="Remove">Remove</a>\ 
      <br>\ 
      <input type="text" class="ChampionInput" list="champions" name="champion[]" placeholder="Champion '+championNumber+'">\ 
      <datalist id="champions"></datalist>\ 
      <a href="#" class="AddSpell">Add Spell</a>\ 
      <a href="#" class="AddGeneralChange">Add General Change</a>\ 
      <div class="GeneralChanges">\ 
      </div>\ 
      <div class="SpellChanges">\ 
      </div>\ 
      <br>\ 
     <div>'); 
     for(var key in champions){ 
      if(champions.hasOwnProperty(key)){ 
       $('#champions').append('<option value="' + key + '">'); 
      } 
     } 
     championNumberArray++; 
     championNumber++; 
    }); 
}); 

和索引

<div id="wrap"> 
    <a href="#" id="AddChampion">Add Champion</a> 
    <form name="second_form" id="second_form" method="POST"> 
     <div id="ChampionInput"> 
     </div> 
     <br><br> 
     <input type="submit" name="submit"> 
    </form> 
</div> 

回答

0

你有重新编号inp当你删除一个。尝试下面的内容。

$('div#ChampionInput').on('click', 'a.Remove',function(){ 
    var champion = $(this).closest('.Champion'); 
    var id = champion.data("id"); 
    var nextChampion = champion; 

    // 
    // Loop through each following champion 
    while((nextChampion = nextChampion.next()).length != 0){ 
     // Update id 
     nextChampion.attr("data-id",id++) 

     // Update placeholder 
     // Placeholder is id + 1 because placholders start at 1 and ids start at 0 
     nextChampion.find(".ChampionInput").attr("placeholder","Champion " + (id + 1));   
    } 

    // Remove champion 
    champion.remove(); 

}); 

顺便说一句,你不需要在选择器之前有标记名。特别是对于每个页面应该是唯一的ID。 #ChampionInputdiv#ChampionInput完全相同,除了#ChampionInput更快,因为浏览器不必检查tagName是否匹配。

+0

那完美的作品,但有什么方法可以相应地快速改变占位值? – Higeath

+0

我更新了它,所以它也更新了占位符。但看起来你也必须改变你的添加代码,以便新的冠军输入拥有合适的占位符。新冠军可能也会添加错误的ID。如果它有帮助,可以使用'$(“。ChampionInput”).length'来获得冠军的数量以计算这些值。 –

0

你不应该使用championNumberArray和championNumber来存储输入数量,而不是你应该计算所有的div与'Champion'类来获得当前数量。

$("div.Champion").length; 

当输入添加时,你应该使用上面的方法设置“id”值。


当输入被删除,U应在删除之前得到疗法 “ID” 值...取出后,美国可以做以下的((假设 “3” 已删除))

var c=3-1, el; 

while(el=$("div.Champion:eq("+c+")").get()) 
{ $(el).data("id",c+1); c++; }