Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

javascript - Hovering over an <option> in a select list

I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.

Relevant code:

Select chunk of form:

<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>

Manipulating selects (arrays defined earlier):

function rankFeatures(create) {

    var $optionList = $("#optionList");
    var $ranks = $("#ranks");

if(create == true) {
    for(i=0; i<5; i++){
        $optionList.append(features[i]);
    };
}
else {
    var index = $optionList.val();
    $('#optionList option:selected').remove();
    $ranks.append(features[index]);
};

}

This all works. It all falls apart when I try to deal with hovering over options:

$(document).ready( 

function (event) {
$('select').hover(function(e) {
    var $target = $(e.target);
    if($target.is('option')) {
        alert('yeah!');
    };
})
})

I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up. I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?

Thanks for reading!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the mouseenter event.

And you do not have to use all this code to check if the element is an option.

Just use the .on() syntax to delegate to the select element.

$(document).ready(function(event) {
    $('select').on('mouseenter','option',function(e) {
        alert('yeah');
        // this refers to the option so you can do this.value if you need..
    });
});

Demo at http://jsfiddle.net/AjfE8/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...