代码一:
$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/