在选择选项上绑定点击事件

我在HTML option元素上发生click事件时遇到了问题。

即使是简单的console.log('hello!'); 不行。

我正在尝试这个:

 $('#mySelect option').bind('click', function(){ console.log('hi!'); }); 

它工作了一段时间,但后来停了下来。

在我的情况下代码工作

 $('#myItem').change(function(){ //do somthing }) 

您可以使用.on()通过提供 id进行绑定。 通常, change是在调用的事件。

因此,绑定事件时无需提及option

 $(document).on('change','#mySelect', function(){
console.log('hi!'); });

要么

 $('#mySelect').bind('change',function(){
console.log('hi!'); });

检查这个js小提琴 –

http://jsfiddle.net/4W826/

HTML

  

JQUERY

 $('#mySelect').bind('click', function(){ alert('hi!'); }); 

Click ChangeChange

示例将显示如何在单击或更改选择时更改OPTION的下拉值和颜色

HTML:

  

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()); }); 

演示

这解决了这种情况 – 根据我的需要(在点击我页面上的某些select元素时捕获事件)。 虽然没有validation触摸行为但Firefox,Chrome似乎没问题

 $('.class_for_select').focus(function() { // do something here }); 

我建议你使用.on()而不是.bind()。

 $('#mySelect').on('change', function(){ var $this = $(this), $value = $this.val(); alert($value); }); 

的jsfiddle

因为改变对我来说不够好,而且我找不到触发选项的方法点击我所做的就是

  $('#mySelect').click(function () { if ($(this).attr('optionclick') == '1') { $(this).attr('optionclick', '0'); } else { $(this).attr('optionclick', '1'); } });