如何防止选择添加到选择元素的新选项?

时间:2020-05-25 08:25:21

标签: javascript html jquery

我正在添加新选项来选择标签,但我不想选择其中任何一个。我尝试了几种方法,但是每次选择第一个选项时。这是代码:

const $selectField = $('.clsname');
const array = ['option1', 'option2', 'option3'];
$selectField.empty();
array.forEach(function(iter, elem) {
  $selectField.append(new Option(iter, elem, false, false));
});
$selectField.show();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select hidden class="clsname"></select>

据我了解,将new Option()defaultSelected一起使用并将其设置为false应该可以解决问题。

此外,我尝试在forEach之后添加类似的内容,但是它也不起作用。

$selectField.children("option:selected").prop("selected", false);

1 个答案:

答案 0 :(得分:1)

添加选项后,可以将选择字段的值设置为parameters: - name: debugMachine displayName: 'Run on selected agent:' type: string default: 'Auto Select From Pool' values: - 'Auto Select From Pool' - 'MACHINE01' - 'MACHINE02' - 'MACHINE03' - 'MACHINE04' - 'MACHINE05' jobs: -job: build # ----------------------------------------------------------------------------------------------- # This is the pool selection section if a specific debug machine is passed in via the params # It will select that specific one to run the build on. unfortunately azure doesnt let you pass # vars or params to the process string in the demands which would have made this alot cleaner. pool: name: 'YOUAGENTSPOOLNAME' ${{ if ne(parameters.debugMachine, 'Auto Select From Pool') }}: ${{ if eq(parameters.debugMachine, 'MACHINE01') }}: demands: - Agent.Name -equals MACHINE01 ${{ if eq(parameters.debugMachine, 'MACHINE02') }}: demands: - Agent.Name -equals MACHINE02 ${{ if eq(parameters.debugMachine, 'MACHINE03') }}: demands: - Agent.Name -equals MACHINE03 ${{ if eq(parameters.debugMachine, 'MACHINE04') }}: demands: - Agent.Name -equals MACHINE04 ${{ if eq(parameters.debugMachine, 'MACHINE05') }}: demands: - Agent.Name -equals MACHINE05 steps: - script: "echo finally it works"

null

$('#mySelect').val(null)
for(var i = 1; i < 5; i++) {
	$option = $('<option></option>').text('Option ' + i).val(i);
	$('select').append($option);
}
$('select').val(null)