使用jquery添加新项目时如何删除最后一个子项

时间:2017-03-06 06:21:30

标签: jquery append

我喜欢用jquery添加dinamic li。我想在达到3时删除最后一个位置$(document).ready(function() { $('.search').on('click', function() { var text = $('#person').val(); var li_count = $('ul.history li').length; $('#person').val(''); if (li_count < 3) { $('ul.history').prepend('<li><a href="' + text + '">' + text + '</a></li>'); } else { $('ul.history li:last-child').remove(); } }); });,并在输入新值时保持追加。但是删除最后一个位置我有问题。

是否有任何建议在添加新项目时如何删除最后位置 感谢

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="person" type="text">
<button class="search">search</button>
<ul class="history">
</ul>
&#13;
awk -F'|' '{$1=$2=$3="";sub(/^[[:space:]]+/,"");print}'  HIRE_PURCHASE_testing.csv > farahjihan.csv
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

你在那里,总是在搜索到的文本前面加上条件并删除条件。

$('ul.history').prepend('<li><a href="' + text + '">' + text + '</a></li>');
if (li_count >= 3){
  $('ul.history li:last-child').remove();
}

&#13;
&#13;
$(document).ready(function() {
  $('.search').on('click', function() {
    var text = $('#person').val();    
    $('#person').val('');    
    $('ul.history').prepend('<li><a href="' + text + '">' + text + '</a></li>');
    
    //Take latest length
    var li_count = $('ul.history li').length;
    if (li_count > 3){
      $('ul.history li:last-child').remove();
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="person" type="text">
<button class="search">search</button>
<ul class="history">
</ul>
&#13;
&#13;
&#13;