jQuery 在选择选项上绑定点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12275153/
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
Bind click event on select option
提问by Salvatore Dibenedetto
I've got a problem making a click
event on an HTML option
element work.
我在处理click
HTMLoption
元素上的事件时遇到问题。
Even a simple console.log('hello!');
won't work.
即使是简单的console.log('hello!');
也行不通。
I am trying with this:
我正在尝试这样做:
$('#mySelect option').bind('click', function(){
console.log('hi!');
});
It worked for a while, but then stopped.
它工作了一段时间,但后来停止了。
回答by Mohsin Saeed
In my case following code works
在我的情况下,以下代码有效
$('#myItem').change(function(){
//do somthing
})
回答by Prem
You can bind using .on()
by giving <select>
id. In general, change
is the event called upon <select>
.
您可以.on()
通过提供<select>
id来绑定 using 。一般情况下,change
是调用的事件<select>
。
So, there is no need to mention option
while binding event.
因此,无需提及option
while 绑定事件。
$(document).on('change','#mySelect', function(){<br>
console.log('hi!');
});
OR
或者
$('#mySelect').bind('change',function(){<br>
console.log('hi!');
});
回答by user3472193
This solve the case - for my needs (to catch the event when some of the select element on my page is clicked). Have not validated touch behavior though but Firefox, Chrome seems to be OK w/ this
这解决了这个问题 - 满足我的需要(在单击我页面上的某些选择元素时捕获事件)。尚未验证触摸行为,但 Firefox、Chrome 似乎没问题
$('.class_for_select').focus(function() {
// do something here
});
回答by nadeem
Sample example will show how to change dropdown values and color for the OPTION on click or change of select
示例示例将展示如何在单击或更改选择时更改选项的下拉值和颜色
HTML:
HTML:
<select name="options">
<option value="1">Red</option>
<option value="2" selected="1">Green</option>
<option value="3">Blue</option>
</select>
jQuery:
jQuery:
$("select").on("click", function () {
debugger;
var sVal = $(this).val();
$(this).css("background-color", "red");
$(this).find("option").css("background", "white");
$(this).find('option:selected').css("background-color", "red");
$("input").val($(this).val());
});
回答by swapnesh
Check this js fiddle --
检查这个js小提琴-
HTML
HTML
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
JQUERY
查询
$('#mySelect').bind('click', function(){
alert('hi!');
});
Change from Click
to Change
更改Click
为Change
回答by JanHocevar
回答by user1715617
because change not good enough for me and I didn't find a way to trigger the option click what I did is
因为改变对我来说不够好而且我没有找到触发选项的方法点击我所做的是
$('#mySelect').click(function () {
if ($(this).attr('optionclick') == '1') {
$(this).attr('optionclick', '0');
}
else {
$(this).attr('optionclick', '1');
}
});