2012-02-04 101 views
11

我想在鼠標光標懸停時提醒一個選項。我使用此代碼:jQuery-選擇列表選項懸停

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

不幸的是,這既不在IE中也不在FF中工作。

有人可以給我一個提示嗎?

+1

檢查下面的鏈接,有用的信息http://stackoverflow.com/questions/2064011/select-option-hover-is-not-working-in-ie – kobe 2012-02-04 19:48:58

+0

一個更多http://stackoverflow.com/questions/4599975/html-select-box-options-on-hover – kobe 2012-02-04 19:49:10

回答

19

你可以試試這個。

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

原因是Chrome和IE不會讓你直接捕獲事件在選項元素上,但確實允許您捕獲選定元素上的事件。 – 2012-02-04 20:58:12

+0

這是非常好的,謝謝Shankar :) – enne87 2012-02-05 16:51:14

+0

我正在努力與IE 8;我只是沒有看到選項中的鼠標懸停或事件,只是選擇。似乎在Chrome和FF中工作,但不在IE中。 (「#」+ id).closest(「。t-palette」)。find(「select」)。hover(function(event){Tungstencon.debug(「hover」+ this.id ); var $ target = jQuery(event.target); if($ target.is(「option」)){ T5.console.debug(「option =」+ $ target.text()); this .title = $ target.text(); } }); – 2012-07-10 22:41:05

4

如果你犯了一個「列表框」類型選擇框中添加一個「大小= x」的屬性是這樣的:

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

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

懸停事件將在選項元素工作

+1

不工作的朋友.. IE瀏覽器,Safari瀏覽器和鉻.. :( – 2013-09-13 01:47:45

+1

測試工作在safari和鉻 - 沒有測試IE瀏覽器 - http:// jsfiddle.net/TJ6Fz/ – 2013-09-13 14:06:32

+0

現在偉大的刪除大小,並再次在Chrome上測試@A_funs – 2013-09-16 00:55:25

1

這裏有一個解決辦法(相當不錯的我猜的) -

  • 使用mouseover事件將選擇框的大小設置爲等於no。其子女
  • 使用mouseenter事件來獲得選項。在選項mouseenter作品完全當size屬性是存在的(我們都知道現在)
  • 使用mouseout事件選擇框的大小重新設置爲1,讓我們的正常選擇框後面:)

JSFiddle