Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...