2017-03-06 82 views
0

我喜欢用jquery添加注释。我想在达到3时删除最后一个位置li,并在输入新值时继续追加。但我有删除最后一个位置的问题。如何使用jquery添加新项目时删除最后一个孩子

有任何建议如何删除最后一个位置时 感谢

$(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(); 
 
    } 
 
    }); 
 
});
<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>

回答

4

你有没有增加新项目,总是在前面加上搜索的文本,如果达到条件删除。

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

$(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(); 
 
    } 
 
    }); 
 
});
<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>

+0

我想我还需要别人来删除最后一个项目。我明白了,所以它会在到达3时删除最后一个项目。感谢您的建议 – rnDesto

相关问题