从HTMLCollection获取值到字符串 [英] Getting values from an HTMLCollection to a string
问题描述
我正在尝试获取多选下拉列表的选定值,并将其转换为单个字符串以供以后操作。目前,我有以下代码:
function newComic(){var elem = document.querySelector(#genreList)。selectedOptions; var arr = [] .slice.call(elem); var genres = arr.join(’,’); window.alert(genres); }
< select id = genreList multiple =多个 name = addGenre [] style = width:150px; font-size:10pt;> < option value = Action> Action< / option> < option value =喜剧>喜剧< / option> < option value = Fantasy> Fantasy< / option> < option value = Horror> Horror< / option> < option value =神秘>神秘< / option> < option value = Non-Fiction> Non-Fiction< / option> < option value = Period> Period< / option> < option value = Romance> Romance< / option> < option value = Sci-Fi> Sci-Fi< / option> < option value = Thriller> Thriller< / option> < / select>< / p> < p><输入type = button onclick = newComic() value =添加漫画 id = btnAddComic style = font-size:10pt;宽度:150px;高度:40px;> < / p>
警报窗口当前输出以下内容:
[object HTMLOptionElement,object HTMLOptionElement,...]
其中'...'代表任何进一步的假设选项。 / p>
我需要的是将流派输出为例如动作,浪漫,惊悚。
预先感谢您的帮助。
当您加入
数组,它正在调用每个元素的 toString。在这种情况下,它们是DOM元素并返回其类型。您可以使用 map
首先创建一个新的字符串数组,其中包含每个选项的值
:
var genres = arr.map(function(el){
return el.value;
})。join(',');
I am attempting to grab the selected values of a multi-select dropdown and convert them into a single string for later manipulation. At the moment I have the following code:
function newComic()
{
var elem = document.querySelector("#genreList").selectedOptions;
var arr = [].slice.call(elem);
var genres = arr.join(', ');
window.alert(genres);
}
<select id="genreList" multiple="multiple" name="addGenre[]" style="width: 150px;font-size: 10pt;">
<option value="Action">Action</option>
<option value="Comedy">Comedy</option>
<option value="Fantasy">Fantasy</option>
<option value="Horror">Horror</option>
<option value="Mystery">Mystery</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Period">Period</option>
<option value="Romance">Romance</option>
<option value="Sci-Fi">Sci-Fi</option>
<option value="Thriller">Thriller</option>
</select></p>
<p><input type="button" onclick="newComic()" value="Add Comic" id="btnAddComic" style="font-size: 10pt; width: 150px; height:40px;"></p>
The alert window is currently outputting the following:
[object HTMLOptionElement, object HTMLOptionElement, ...]
where '...' represents any further hypothetical options.
What I need is for 'genres' to output as, for example, 'Action, Romance, Thriller' instead.
Thanks in advance for any help.
When you join
the array, it is calling the "toString" of each element. In this case, they are DOM elements and return their type. You can use map
first to create a new array of strings containing the value
of each option:
var genres = arr.map(function(el){
return el.value;
}).join(', ');
这篇关于从HTMLCollection获取值到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!