gpt4 book ai didi

javascript - 保存所选元素的 ID

转载 作者:行者123 更新时间:2023-11-28 20:10:13 26 4
gpt4 key购买 nike

嘿,我这里有一个小 list :

<ul id="selectable">
<li id='id.00'></li>
<li id='id.10'></li>
<li id='id.20'></li>
<li id='id.30'></li>
<li id='id.40'></li>
<li id='id.50'></li>
<li id='id.60'></li>
<li id='id.70'></li>
<li id='id.80'></li>
<li id='id.90'></li>
</ul

我可以使用 css 选择一个或多个列表元素:

ul {overflow:hidden;}
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: black; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 300px; }
#selectable li {float: left; width: 30px; height: 20px; background-color: none; display:block; }

现在我想使用 jquery 保存所有选定元素的 id:

$(function() {
$( "#selectable" ).selectable({
stop: function() {
var result = $( "#select-result" ).empty();
$( ".ui-selected", this ).each(function() {
var index = $(this).attr('id');
result.append( index );
alert(index);
});
}
});
});

好的,到目前为止一切顺利:当我选择例如四个列表元素,它们被标记,但是:只保存最后一个 id。例如,当我选择此列表元素时:

<li id='id.00'></li>
<li id='id.10'></li>
<li id='id.20'></li>
<li id='id.30'></li>

只有 id:“id.30”保存在我的变量“index”中。我怎样才能让我的 jquery 保护所选元素的所有 id 而不仅仅是最后一个?问候!

最佳答案

尝试.map()

var result = $(".ui-selected", this).map(function () {
return this.id;
}).get();

注意:这将返回数组

<小时/>如果你想获取字符串使用 .join()

var result = $(".ui-selected", this).map(function () {
return this.id;
}).get().join(',');
<小时/>

在OP评论后更新

fiddle Demo

$(function () {
$("#selectable").selectable({
stop: function () {
var result = $(".ui-selected", this).map(function () {
return this.id;
}).get().join(',');
$('#select-result').html(result);
}
});
});

关于javascript - 保存所选元素的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20021132/

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