简体   繁体   中英

How to change 'hover' function to 'on' function?

I need to use 'on' function instead of 'hover'. It's old code:

        $('.field').hover(
        function() 
        {
            old_value=$(this).text();
            item_id=$(this).attr('id');
            item=$(this).parent('td');
            new_value=(old_value=='Not translated') ? '' : old_value;

            $(this).empty(); 
            var field="<div id='save_button' class='btn btn-primary' style='float: right' href='#'>Save</div><form>"+
                "<div style='overflow: hidden; padding-right: .5em;'>"+
                "<input id='new_value' type='textarea' name='term' style='width: 100%;' value='"+new_value+"'/></div></form>";
            $(this).html(field);
        },
        function() 
        {

            $(this).empty();
            $(this).html(old_value);
        });

And it's new code:

        $('.field').on('hover',
        function(event) 
        {
            old_value=$(this).text();
            item_id=$(this).attr('id');
            item=$(this).parent('td');
            new_value=(old_value=='Not translated') ? '' : old_value;

            $(this).empty(); 
            var field="<div id='save_button' class='btn btn-primary' style='float: right' href='#'>Save</div><form>"+
                "<div style='overflow: hidden; padding-right: .5em;'>"+
                "<input id='new_value' type='textarea' name='term' style='width: 100%;' value='"+new_value+"'/></div></form>";
            $(this).html(field);
        },
        function(event) 
        {

            $(this).empty();
            $(this).html(old_value);
        });

Old code works good, but new one doesn't work (only mouseout function works). Please, tell me, where have I made a mistake? Thank you.

The easiest thing to do is probably to bind to mouseenter and mouseleave separately (which is just what hover does anyway). Here's the jQuery source of the .hover() method :

function (fnOver, fnOut) {
    return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
}

You can pass a map of event names to event handlers to .on() :

$('.field').on({
    mouseenter: function (event) {
        // First function passed to hover
    },
    mouseleave: function (event) {
        // Second function passed to hover
    }
});

But there is nothing wrong with .hover() , so you could just stick with that.

According to jQuery API Documentation , "hover" pseudo-event name (used for "mouseenter mouseleave") is deprecated since v1.8 and you must use two event handlers instead of :

$('.field').on({mouseenter: function (e) { /* code */ },
                mouseleave: function (e) { /* code */ }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM