如何模拟选项选择?click() 不起作用

huangapple go评论65阅读模式
英文:

How to simulate option selection? click() doesn't work

问题

我想模拟用户单击某个选项,所以我使用click()来点击<option>,但它不起作用。

let select = document.getElementById("select");
select.addEventListener("change", changeSelection);

function changeSelection() {
  console.log("Clicked");
}

let option = select.querySelector('option[value="3"]');
option.click();

如何做到这一点?

英文:

I want to simulate a user click on certain option, so I use click() on the &lt;option&gt; but it doesn't work:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let select = document.getElementById(&quot;select&quot;);
select.addEventListener(&quot;change&quot;, changeSelection);

function changeSelection() {
  console.log(&quot;Clicked&quot;);
}

let option = select.querySelector(`option[value=&quot;3&quot;]`);
option.click();

<!-- language: lang-html -->

&lt;select id=&quot;select&quot;&gt;
  &lt;option value=&quot;1&quot;&gt;1&lt;/option&gt;
  &lt;option value=&quot;2&quot;&gt;2&lt;/option&gt;
  &lt;option value=&quot;3&quot;&gt;3&lt;/option&gt;
&lt;/select&gt;

<!-- end snippet -->

How can I do it?

答案1

得分: 3

的值,要么如果是多选

let select = document.getElementById("select");
select.addEventListener("change", changeSelection);

function changeSelection() {
  console.log("Clicked", this.value);
}

select.value = 3;
select.dispatchEvent(new Event('change'));
<select id="select">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

多选

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定