重构以避免 setTimeout 函数

Refactor to avoid the setTimeout function

本文关键字:setTimeout 函数 重构      更新时间:2023-09-26

我想附加一个事件处理程序,当将鼠标悬停在项目上时,它将在它附加到的项目周围放置一个边框。如果可能的话,我想避免使用函数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);
        });
    }
});

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

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