将事件处理程序绑定到HTML select.选项
Binding an event handler to an HTML select.option
如果用户选择了特定选项,但没有显示警告,我想显示一条警告消息。如何修改我的代码以使其正常工作?这是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');
}
}
小提琴
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
相关文章:
- 在html Select中添加搜索
- HTML SELECT-使用JavaScript按VALUE更改所选选项
- 如果值为空或0,如何更改html select标记的边框颜色
- 将递增变量添加到Html Select的Id中
- Call a class constructor from HTML <select>
- 通过Jquery将项目添加到HTML Select
- AngularJS使用HTML select标记选择整数值
- React 和 HTML Select-component 返回 String 而不是 Integer 的最佳方式
- Java servlet 无法读取 html select 标记名称
- HTML Select 字段通过 ajax 调用 Web 服务
- jQuery.when based on html select
- 使用jQuery获取HTML select选项的索引值
- 将HTML Select附加到输入,并在用户单击“保存”按钮后存储它们的值.我正在处理的
- html select上的MouseUp()事件不起作用
- 如何获得strut<html:select>jsp中java脚本中的值
- HTML select元素不会't显示更新的选定属性
- 从html select执行Javascript函数
- 将事件处理程序绑定到HTML select.选项
- 解析.txt文件以使用jQuery填充html select
- 带有jQuery Selector的HTML Select不起作用