问题
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