gpt4 book ai didi

javascript - 使用jquery从数组中删除特定值之后的所有值

转载 作者:行者123 更新时间:2023-11-28 14:50:47 25 4
gpt4 key购买 nike

考虑到将一周中的几天列表转换为数组,我可以在单击它时从数组中提取其中任何一天的值。但是,我找不到任何有关如何从数组中删除单击的值之后的所有值的信息:

  • 例如,当点击 ID 为 friday 的 li 时,删除 #saturday#sunday

如果您知道如何操作,请告诉我,并提前感谢大家的时间和关注。

HTML:

<ul>
<li id="monday">Monday</li>
<li id="tuesday">Tuesday</li>
<li id="wednesday">Wednesday</li>
<li id="thursday">Thursday</li>
<li id="friday">Friday</li>
<li id="saturday">Saturday</li>
<li id="sunday">Sunday</li>
</ul>

jQuery:

var floorIds = new Array('#monday', '#tuesday', '#wednesday', '#thursday', '#friday', '#saturday', '#sunday');

$('ul li').on('click', function() {
var which = $(this).attr('id');
var newFloorIds = floorIds;
var floorPos = newFloorIds.indexOf('#'+floorId);
newFloorIds.length = floorPos + 1;
console.log(newFloorIds, floorIds);
});

最佳答案

您可以找到数组中元素的位置:

var elementPosition = floorIds.indexOf('#'+$(this).attr('id'));

然后将数组长度设置为索引+1

floorIds.length  = elementPosition + 1; //as index are zero based

$('ul li').on('click', function() {
var floorIds = new Array('#monday', '#tuesday', '#wednesday', '#thursday', '#friday', '#saturday', '#sunday');
var elementPosition = floorIds.indexOf('#'+$(this).attr('id'));
floorIds.length = elementPosition + 1;
console.log(floorIds)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="monday">Monday</li>
<li id="tuesday">Tuesday</li>
<li id="wednesday">Wednesday</li>
<li id="thursday">Thursday</li>
<li id="friday">Friday</li>
<li id="saturday">Saturday</li>
<li id="sunday">Sunday</li>
</ul>

关于javascript - 使用jquery从数组中删除特定值之后的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44586341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com