jQuery click事件未在optgroup上触发 [英] jQuery click event not firing on optgroup

查看:205
本文介绍了jQuery click事件未在optgroup上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码-jsFiddle上的示例

I have the following code - example on jsFiddle

<select>
 <optgroup label="Group1">
   <option value="11">Option 1</option>
   <option value="12">Option 2</option>
 </optgroup>
 <optgroup label="Group2">
   <option value="21">Option 1</option>
   <option value="22">Option 2</option>
 </optgroup>
</select>​

和一些jquery代码:

and some jquery code:

$(document).ready(function() {
$("select optgroup").click(function() {
    alert("Clicked " + $(this).attr("label"));            
});

这似乎很简单.如果我添加onclick="javascript:alert(...);"似乎可行...除了点击无论点击什么都会触发.

This seems pretty straight forward. If I add onclick="javascript:alert(...);" that seems to work ... except that the click fires no matter what is clicked.

为什么这行不通?

感谢您的帮助!

编辑

似乎我在这里尝试做的事情有误解,所以我需要稍微扩展代码以给出更好的主意.

It seems there is a misunderstanding in what I'm trying to do here so I need to expand the code a bit to give a better idea.

我要拍摄的是能够执行以下操作:

What I'm shooting for is to be able to do the following:

$(document).ready(function() {
   $("select optgroup").children().hide();
   $("select optgroup").click(function() {
      $(this).children().show();
   });

如您所见,在选项上捕获一个click事件,然后确定组将不起作用,因为所有选项都将被隐藏.当您单击组"(optgroup)时,我希望显示这些选项.话虽如此,Chrome似乎并不尊重对组的单击,而IE只会返回所选项目的组(当您单击optgroup时).

As you can see, trapping a click event on the option and then determining the group won't work because the options will all be hidden. I want the options displayed when you click the Group (optgroup). Having said that, Chrome doesn't seem to respect a click on the group and IE only returns the group of the selected item (when you click an optgroup) item.

推荐答案

所以对此的简短回答似乎是这是不可能的.无法使用optionGroups进行常规选择,然后将其转换为手风琴样式的选择列表,在此列表中最初仅显示选项组项目,然后单击选项组项目会展开其子项(选项).

So the short answer on this seems to be that this is not possible. It is not possible to take a normal select with optionGroups and turn it into an accordion styled select list where initially, only the optiongroup items are displayed and clicking an optiongroup item expands its children (the options).

似乎没有浏览器真正支持单击选择列表中的组项目.当发生onClick事件时,该事件的行为就好像您单击了所选项目一样.

It seems that no browsers truly support clicking a group item in the select list. While there is an onClick event, the event acts more like you've clicked the selected item.

这篇关于jQuery click事件未在optgroup上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆