jQuery-Select 列表选项悬停

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9143924/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:23:44  来源:igfitidea点击:

jQuery-Select list option hover

jquery

提问by enne87

I want to alert an option when the mouse-cursor is over it. I use this code:

当鼠标光标在它上面时,我想提醒一个选项。我使用这个代码:

$("select > option").hover(function ()
    { 
        alert($(this).attr("id"));
    });

Unfortunately, this is neither working in IE nor in FF.

不幸的是,这既不适用于 IE,也不适用于 FF。

Can someone give me a hint please?

有人可以给我一个提示吗?

回答by ShankarSangoli

You can try this.

你可以试试这个。

$("select").hover(function (e)
{
     var $target = $(e.target); 
     if($target.is('option')){
         alert($target.attr("id"));//Will alert id if it has id attribute
         alert($target.text());//Will alert the text of the option
         alert($target.val());//Will alert the value of the option
     }
});

回答by A_funs

If you make a "listbox" type select box by adding a "size=x" attribute like this:

如果您通过添加“size=x”属性来创建“列表框”类型的选择框,如下所示:

<select size="3">
   <option>...</option>
   <option>...</option>
</select>

The hover event will work on the option elements:

悬停事件将作用于选项元素:

$('option').hover(function(){
     //code here
});

回答by Sahil Mittal

Here's a workaround (quite decent I guess)-

这是一个解决方法(我想相当不错)-

  • Use mouseoverevent to set the size of the select box equal to the no. of its children
  • Use mouseenterevent to get the options. mouseenterworks on options perfectly when sizeattribute is there (we all know that now)
  • Use mouseoutevent to set the size of the select box back to 1, to get our normal select box back :)
  • 使用mouseoverevent 将选择框的大小设置为等于 no。它的孩子
  • 使用mouseenter事件来获取选项。mouseentersize属性存在时完美地处理选项(我们现在都知道)
  • 使用mouseout事件将选择框的大小设置回1,以恢复我们正常的选择框:)

JSFiddle

JSFiddle