【问题标题】:jQuery-Select list option hoverjQuery-选择列表选项悬停
【发布时间】:2012-02-04 19:41:54
【问题描述】:

我想在鼠标光标悬停时提醒一个选项。我使用此代码:

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

不幸的是,这在 IE 和 FF 中都不起作用。

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

【问题讨论】:

标签: jquery


【解决方案1】:

你可以试试这个。

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

【讨论】:

  • 原因是 Chrome 和 IE 不允许您直接在选项元素上捕获事件,但允许您在选择元素上捕获事件。
  • 我正在为 IE 8 解决这个问题;我只是没有从选项中看到鼠标悬停或悬停事件,只是选择。似乎适用于 Chrome 和 FF,但不适用于 IE。 jQuery("#" + id).closest(".t-palette").find("select").hover(function (event) { T5.console.debug("hover" + this.id); var $ target = jQuery(event.target); if ($target.is("option")) { T5.console.debug("option = " + $target.text()); this.title = $target.text( ); } });
  • 它对我不起作用..我正在尝试相同的代码。当我将鼠标悬停在选项上时,它不会发出警报。 .
【解决方案2】:

如果您通过像这样添加“size=x”属性来制作“列表框”类型的选择框:

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

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

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

【讨论】:

  • 在 safari 和 chrome 中测试工作 - 没有测试 IE - jsfiddle.net/TJ6Fz
  • 伟大的现在删除大小并在 chrome @A_funs 上再次测试它
  • @Tarun Idk 你的牛肉在这里,我的回复说你需要包含 size 属性才能工作,当你这样做时 - 它工作......
【解决方案3】:

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

  • 使用mouseover事件将选择框的大小设置为等于no。它的孩子
  • 使用mouseenter 事件获取选项。当size 属性存在时,mouseenter 可以完美地处理选项(我们现在都知道了)
  • 使用mouseout事件将选择框的大小设置回1,以恢复我们正常的选择框:)

JSFiddle

【讨论】: