我正在尝试在 MultiSelect 控件上使用 Select2 jQuery 库。这些控件工作正常,但我需要更改 select2 用于多选控件的值的默认定界符(分隔符)。
当前从多选控件的值中检索值的输出是
comma
,我需要它是semi-colon
分隔值,这该怎么办?
$("#btn").click(function(e) {
e.preventDefault();
$("#result").text('Output: ' + $("#example1").select2("val"));
});
$("#example1").select2({
seperator: ";"
});
#btn {
margin: 20px 0px;
}
#result {
margin: 20px 0px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>
<select id="example1" placeholder="Select ..." class="" style="width:100%;" multiple="multiple">
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
<option value="Option 4">Option 4</option>
<option value="Option 5">Option 5</option>
<option value="Option 6">Option 6</option>
</select>
<input type="button" id="btn" value="Click Me" />
<div id="result">Output:
</div>
既然您提到您的选项值可能包含逗号,我原来的答案将不起作用。请尝试此操作(出于演示目的,我已在您的选项值中添加了逗号):
$("#result").text('Output: ' + $("#example1").select2("val").join(';'));
$("#btn").click(function(e) {
e.preventDefault();
$("#result").text('Output: ' + $("#example1").select2("val").join(';'));
});
$("#example1").select2();
#btn {
margin: 20px 0px;
}
#result {
margin: 20px 0px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>
<select id="example1" placeholder="Select ..." class="" style="width:100%;" multiple="multiple">
<option value="Option, 1">Option 1</option>
<option value="Option, 2">Option 2</option>
<option value="Option, 3">Option 3</option>
<option value="Option, 4">Option 4</option>
<option value="Option, 5">Option 5</option>
<option value="Option, 6">Option 6</option>
</select>
<input type="button" id="btn" value="Click Me" />
<div id="result">Output:
</div>
这也适合我..
.select2-selection__choice {
&:not(:nth-last-child(-n + 2)):after {
content: ',';
}
}