Bootstrap-select 插件 - 以编程方式触发点击事件

问题描述

如何以编程方式触发点击事件第二个选项(选择电视)? 我使用引导选择插件。 我想模仿与用户点击“电视”选项相同的行为。

我在此链接中的代码https://jsfiddle.net/xzv9qkwe/

(顺便说一句,我试图在这里一个片段,但是当我包含 bootstrap-select 的 CDN 时它会抛出一个异常错误......但它在 jsfiddle 链接中工作正常。如果你能告诉我原因,我还将在此处编辑代码段)。

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Bootstrap-select 插件链接https://developer.snapappointments.com/bootstrap-select/

谢谢。

解决方法

与其倾听点击,不如倾听变化。

如果要使用 click 事件,则需要使用 select 元素以外的其他元素。

const output = document.querySelector("#output");
var changeCntr = 0;

document.querySelector(".selectpicker")
  .addEventListener("change",e => {
    if (e.target.value == "TV") {
      changeCntr++;
      output.innerText = `Changed to TV ${changeCntr} times`;
    }
  });
select {
  font-size: 1.5em;
}

div {
  background-color: lightblue;
  min-height: 1.5em;
  font-size: 1.5em;
}
<select class="selectpicker" data-style="btn-primary">
  <option>Computer</option>
  <option>TV</option>
</select>

<div id="output">

</div>