jQuery-选择列表选项悬停

enn*_*e87 11 jquery

我想在鼠标光标悬停时提醒选项.我用这个代码:

$("select > option").hover(function ()
    { 
        alert($(this).attr("id"));
    });
Run Code Online (Sandbox Code Playgroud)

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

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

Sha*_*oli 20

你可以试试这个.

$("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
     }
});
Run Code Online (Sandbox Code Playgroud)

  • 它不适合我..我正在尝试相同的代码.当我将鼠标悬停在选项上时,它不会发出警报.. (10认同)
  • 原因是Chrome和IE不允许您直接在选项元素上捕获事件,但允许您捕获选定元素上的事件. (2认同)

A_f*_*uns 5

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

<select size="3">
   <option>...</option>
   <option>...</option>
</select>
Run Code Online (Sandbox Code Playgroud)

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

$('option').hover(function(){
     //code here
});
Run Code Online (Sandbox Code Playgroud)

  • @Tarun Idk 你的牛肉在这里,我的回复说你需要包含 size 属性才能工作,当你这样做时 - 它有效...... (2认同)