javascript - jQuery "on"函数事件图优化

标签 javascript jquery optimization

代码一:

$searchBoxParent.on({
    mouseover: function() {
        $this = $(this);
        $this.parent().find(".hlight").removeClass('hlight');
        $this.addClass("hlight");
    },
    mouseout: function() {
        $this = $(this);
        $this.parent().find(".hlight").removeClass('hlight');
    },
    click: function() {
        $this = $(this);
        $searchBox.val($this.text()).focus();
        setCurrentlySearchedText();
        deleteSuggestionsDiv();
    }
},"#searchSuggest div");  

代码二: 在上面的代码中,我想将 mouseover 和 mouseout 函数的两个常见语句减少到一个 block 中以减少冗余。为了实现这一点,我添加了一个功能 -

mouseMovement: function() {
    $this = $(this);
    $this.parent().find(".hlight").removeClass('hlight');
}

并将鼠标悬停更改为 -

mouseover: function() {
    this.mouseMovement;
    $this = $(this);
    $this.addClass("hlight");
}

鼠标移开 -

mouseover: function() {
    this.mouseMovement;
}

推论: 我很困惑,因为第二种情况是将冗余减少到一定程度,但是 $this = $(this);是非常多余的。是否可以为“on”函数声明全局而不是单个函数作用域?另外我想知道你的看法第一个代码好还是第二个代码好..!

最佳答案

声明 $this = $(this) 并不是多余的,它通过使 this 成为一个对象来最大限度地减少 DOM 查询的性能。

这是使用 .on 功能解决问题的一种方法:

$('body').on('mouseover', '.SOMECLASS', function () {
    //code here
})

编辑: 我可以看到我还应该解释一下,您只需要声明一次 $this = $(this) 即可。一旦声明了对象,就不再访问 DOM 对象,而是访问 javascript/jQuery 对象,您可以在其上使用 $this.parent(... 等函数。

您的代码当前正在进行冗余声明,这是正确的。将声明嵌套在 .on 函数中,但位于将使用该对象的函数之外/之前。

关于javascript - jQuery "on"函数事件图优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21708951/

相关文章:

javascript - 第三方REST API基础认证

javascript - 使用 jsrender 模板嵌入脚本

javascript - 如何在 jQuery 中同时使用 OR 和 .find() ?

javascript - 当一个元素被另一个元素覆盖时,有没有办法获得鼠标悬停事件?

python/pandas 线性规划/优化挑战

debugging - 在 Scala 中调试日志而不影响性能

c++ - 为什么 Clang 优化掉 x * 1.0 而不是 x + 0.0?

javascript - 为什么 javascript 在我的选择选项上看不到 "selected"属性?

php - 数组作为 Laravel 表单中的输入(提交功能不起作用)

javascript - 将 html 嵌入到另一个站点的技巧