adding onclick event to html select option

时光怂恿深爱的人放手 提交于 2020-02-03 18:59:12

问题


I added onclick event to my select tag like in the following code -

<option onclick="alert('Hello')">Say Hello</option>

but it does not work....

How can I set the option onclick event to fire ?


回答1:


Try it in the onchange handler:

function checkAlert(evt) {
  if (evt.target.value === "Say Hello") {
    alert('Hello');
  }
}
<select onchange="checkAlert(event)">
  <option>Test</option>
  <option>Say Hello</option>
</select>



回答2:


I prefer using Ids to add event listener to separate your code from html so I add an Id to your select tag with "my-select" for example and select this tag by its Id and add onchange event listener. This is the code:

<select id="my-select">
    <option value="1">Say Hello</option>
</select>
<script>
document.getElementById("my-select").addEventListener("change", printMsg);
function printMsg() {
    alert("Hello");
}
</script>



回答3:


you should use onchange event on the select element itself.

<select onchange="alert('hello')">
    <option value="0">Say Hello</option>
    <option value="1">Some other option</option>
</select>

hope that helps,



来源:https://stackoverflow.com/questions/51347363/adding-onclick-event-to-html-select-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!