拆分功能无法正常工作

split function does not work properly

我正在尝试从多个 select 中捕获 selected 项目,以便将它们插入到另一个 select 输入中。问题是,当我尝试使用 split 函数拆分 selected 元素时,控制台会抛出下一个错误:Uncaught TypeError: strValue.split is not a function

HTML

<select multiple id="e9" name="musc_group[]">
    <option value="Chest">Chest</option>
    <option value="Back">Back</option>
</select>

JAVASCRIPT

$("#e9").change(function(){
    var strValues = $(this).val(); // This gives you the string "Chest,Back"
    var arrValues = strValues.split(",");          
});

在活动之外一切正常,但在活动中却不行。

.val() returns select[multiple] 个元素的值数组。

来自文档:

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.

(强调我的)

这意味着你对 // This gives you the string "Chest,Back" 的评论是不正确的,因为你实际上得到了一个你可能正在转换为字符串的数组(使用 alert?)

您已经获得了一组值,原因是在 select 选项中您可以允许多个选择,并且您是通过在 select 上使用 multiple 属性来实现的元素。所以值总是 return 以数组的形式编辑,否则 return 多个值会更好。

所以不用拆分了,已经是数组了

多个select returns一个数组不是一个字符串,

$("#e9").change(function(){
    var strValues = $(this).val(); // This gives you the string "Chest,Back"

    alert(strValues[0]);
    alert(strValues[1]);
});

.val() return 选定元素的数组。所以,你不需要 split 功能。和一个数组元素显示为 , 的字符串连接。你可能会错过理解。