重构以避免setTimeout函数

时间:2014-11-29 21:38:46

标签: javascript html html5 dom

我想附加一个事件处理程序,当项目悬停时,它会在它附加的项目周围放置一个边框。我想尽可能避免使用函数setTimeout()。有没有人有任何想法?感谢我指导一个有用的框架来处理这样的事情。

以下代码是我发现如何执行以下操作的唯一方法。我需要这样做的原因是因为我将抓取元素内部的html并将其替换为db值。这是我的代码:

    var color;
$(document).ready(function(){

    attachMouseEnter();
    // This is not resetting. How do I make it so I can reset this?
    function attachMouseEnter(){
        $('.editable').mouseenter(function(){
            console.log($(this));
            $(this).wrap('<span class="test"></span>')
            $(this).css('border', '1px solid red');
        });
        window.setTimeout(attachMouseOut(), 1000);
    }
    // this is making it so I cannot grab the element and attach a handler to it.
    function attachMouseOut(){
        $('.editable').mouseout(function(){
            var orginal = $(this);
            $(this).css("border", "0px");
            $(this).parent().replaceWith(orginal.parent().html());
            window.setTimeout(attachMouseEnter(), 1000);
        });
    }
});

1 个答案:

答案 0 :(得分:1)

您不必一次又一次地调用事件处理程序。只召唤一次就足够了..

var color;
$(document).ready(function(){
    $('body').on('mouseenter','.editable',function(){
        console.log($(this));
        $(this).wrap('<span class="test"></span>')
        $(this).css('border', '1px solid red');
    });
     $('body').on('mouseout','.editable',function(){
        var orginal = $(this);
        $(this).css("border", "0px");
        $(this).parent().replaceWith(orginal.parent().html());
    });
});
相关问题