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

时间:2014-09-15 12:11:34

标签: javascript html javascript-events

我想在用户选择特定选项时显示警告消息,但警告未显示。如何修改我的代码以使其正常工作?这是一个demo on 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 infomation');
}

3 个答案:

答案 0 :(得分:5)

您无法在下拉选项中使用点击操作。一种解决方案是在select元素上使用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');
    }
}

fiddle

答案 1 :(得分:2)

选项标记不支持onclick事件。改为使用onchange上的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');
  }
}

答案 2 :(得分:1)

你需要在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事件vs CLICK,因为你想对“值的变化”作出反应,如果该值=某事,则警告用户。 使用addEventListener也是一种更好的方法,它可以清楚地区分HTML和JavaScript。

更多相关内容:

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

在这里:

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

相关问题