我想清空我的数据列表,但我不想清除最后五个选项,有没有办法做到这一点?
这是我的代码-
$('#results').empty().append(options);
THANKS IN ADVANCE
要删除jQuery对象中除最后5个元素外的所有元素,您可以使用带负索引的slice()
,如下所示:
$('datalist option').slice(0, -5).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="ice-cream-choice">Choose a flavor:</label>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />
<datalist id="ice-cream-flavors">
<option value="Lorem"> <!-- will be removed -->
<option value="Ipsum"> <!-- will be removed -->
<option value="Dolor"> <!-- will be removed -->
<option value="Sit"> <!-- will be removed -->
<option value="Chocolate">
<option value="Coconut">
<option value="Mint">
<option value="Strawberry">
<option value="Vanilla">
</datalist>