javascript 在 html 选择标签中的选项上添加点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23873302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add click event on an option in html select tag
提问by user3670066
I have a html dropdown defined as
我有一个 html 下拉菜单定义为
<select name="evidence_selected"id="evidence_selected">
<option id="a">A</option>
<option id="b">B</option>
<option id="c">C</option>
<option id="new">New</option>
</select>
I want to fire an on click event on "new" so that when a user clicks on it, a free form appears where they enter some other value that is not on dropdown. The id of the form is "new_value". I tried
我想在“new”上触发一个点击事件,这样当用户点击它时,就会出现一个自由表单,他们在那里输入一些不在下拉列表中的其他值。表单的 id 是“new_value”。我试过
$("#new").click(function(){
$("new_value").show();
});
It seems the click event wont fire. Any help(with code snippet) will be highly appreciated. Regards
似乎点击事件不会触发。任何帮助(使用代码片段)将不胜感激。问候
回答by JakeSidSmith
Selects use the change event
选择使用更改事件
$('select').change(function () {
if ($(this).val() === 'New') {
// Handle new option
}
});
This will trigger any time any of the options are selected.
这将在任何时候选择任何选项时触发。
回答by DarkAjax
I advice doing something like this instead:
我建议做这样的事情:
$('#evidence_selected').change(function(){
if($(this).val() == "New"){
$("#new_value").show();
} else {
$("#new_value").hide();
}
});
This way, the function will be triggered when the value of the select changes, but it'll only show #new_value
if the option <option id="new">New</option>
was selected...
This way, the function will be triggered when the value of the select changes, but it'll only show #new_value
if the option <option id="new">New</option>
was selected...
Also if the ID of your form is new_value
, you should reference it as $("#new_value").show();
instead of $("new_value").show();
(you're lacking the #
)
此外,如果您的表单的 ID 是new_value
,您应该将其引用为$("#new_value").show();
而不是$("new_value").show();
(您缺少#
)
回答by Alex Char
Try this:
试试这个:
html
html
<select name="evidence_selected" id="evidence_selected">
<option id="a">A</option>
<option id="b">B</option>
<option id="c">C</option>
<option id="new">New</option>
</select>
js
js
$("#evidence_selected").change(function(){
if($(this).val()=="new"){
$("new_value").show();
}
});
回答by gurudeb
$("#evidence_selected").on('change', function() {
var optionId = $('option:selected', this).attr('id');
if(optionId === 'new') {
// your action here
}
});