如何将'悬停'功能改为'开'功能?

时间:2012-07-12 07:20:23

标签: javascript jquery

我需要使用'on'功能而不是'hover'。这是旧代码:

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

这是新代码:

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

旧代码运行良好,但新代码不起作用(只有mouseout函数有效)。请告诉我,我在哪里弄错了?谢谢。

2 个答案:

答案 0 :(得分:5)

最简单的事情可能是分别绑定到mouseentermouseleave(这正是hover所做的事情)。这是jQuery source of the .hover() method

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

您可以将事件名称地图传递给.on()的事件处理程序:

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

但是.hover()没有任何问题,所以你可以坚持下去。

答案 1 :(得分:0)

根据jQuery API Documentation,“vover”伪事件名称(用于“mouseenter mouseleave”)自v1.8起不推荐使用,您必须使用两个事件处理程序而不是:

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