将事件处理程序绑定到HTML select.选项

Binding an event handler to an HTML select.option

本文关键字:HTML select 选项 绑定 事件处理 程序      更新时间:2023-09-26

如果用户选择了特定选项,但没有显示警告,我想显示一条警告消息。如何修改我的代码以使其正常工作?这是jsFiddle上的一个演示,它再现了这个问题?

HTML:

<input type="text" id="mail_address"/>
<select>
    <option value='google.com'>google.com</option>
    <option onClick="warningaa()" value=''>Don't send mail</option>
</select>

JS:

function warningaa() {
    alert('If you choose this option, you can not receive any information');
}

您不能在下拉选项中使用点击操作。一种解决方案是在选择元素上使用change

html

<input type="text" id="mail_address" />
<select onchange="warningaa(this);">
    <option value='google.com'>google.com</option>
    <option value='error'>error</option>
</select>

js

function warningaa(obj) {
    if(obj.value == "error") {
        alert('If you choose this option, you can not receive any infomation');
    }
}

小提琴

option标记不支持onclick事件。请改为在select上使用onchange事件。

HTML

<input type="text" id="mail_address"/>
<select id="selectbox" onchange="warning(this)">
  <option value='google.com'>google.com</option>
  <option value='warning'>Do not send me any kind of shit</option>
</select>

JS-

function warning(obj) {
  if(obj.value == 'warning') {
    alert('If you choose this option, you can not receive any infomation');
  }
}

您需要在SELECT元素上设置一个事件处理程序,并观察SELECT的"值",如下所示:

document.getElementById('mySelect').addEventListener('change', warn, true);
function warn(e) {
  e.preventDefault();
  e.stopPropagation();
  if (e.currentTarget.value === 'the value you want') {
    // do something
  } else {
  return;
}

这里的关键是使用CHANGE事件与CLICK,因为您希望对"值的变化"做出反应,如果该值=某个值,则警告用户。总体而言,使用addEventListener也是一种更好的方法,它可以清楚地区分HTML和JavaScript。

更多信息请点击此处:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

这里:

https://developer.mozilla.org/en/docs/Web/API/Event