gpt4 book ai didi

javascript - 使用javascript获取div元素的值并将其放入数组中

转载 作者:行者123 更新时间:2023-11-27 22:44:45 25 4
gpt4 key购买 nike

我有这个 html 代码,我想获取 select2-search-choice div 值的值

<div class="select2-container select2-container-multi form-control multi-select" id="s2id_project_banker_ids">
<ul class="select2-choices">
<li class="select2-search-choice">
<div>Sam Chong</div>
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>
<li class="select2-search-choice">
<div>Beh Li Shiew</div>
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>
<li class="select2-search-field">
<label for="s2id_autogen23" class="select2-offscreen"></label>
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" id="s2id_autogen23" name="s2id_autogen24" placeholder="" data-validate="true" aria-activedescendant="select2-result-label-198" style="width: 42px;">
</li>
</ul>
</div>

到目前为止,我所做的似乎可行,但我正在寻找一种更有效的方法来执行此代码

project_bankers = []
$.each($('#s2id_project_banker_ids').find('li.select2-search-choice'), function(index, choice) {
project_bankers.push(choice.children[0].innerHTML)
})

那么只是检查是否有更有效的方法来做到这一点?

最佳答案

您可以使用 map() 从 jQuery 对象中的一组元素生成数组:

var project_bankers = $('#s2id_project_banker_ids li.select2-search-choice div').map(function() {
return $(this).text();
}).get();

console.log(project_bankers);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select2-container select2-container-multi form-control multi-select" id="s2id_project_banker_ids">
<ul class="select2-choices">
<li class="select2-search-choice">
<div>Sam Chong</div>
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>
<li class="select2-search-choice">
<div>Beh Li Shiew</div>
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>
<li class="select2-search-field">
<label for="s2id_autogen23" class="select2-offscreen"></label>
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" id="s2id_autogen23" name="s2id_autogen24" placeholder="" data-validate="true" aria-activedescendant="select2-result-label-198" style="width: 42px;">
</li>
</ul>
</div>

关于javascript - 使用javascript获取div元素的值并将其放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479823/

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