我已经创建了一个函数。
调整视口大小后,我想完全删除该功能。
off()方法仅删除滚动事件中的代码。
调整视口大小时,它会一直打印“调整大小后仍会执行”。
调整视口大小后是否可以完全删除“ myFunction”,而不会破坏我的功能?
function myFunction(ele) {
myArray = [];
this.num1 = $.each(ele, function(){
var posx = ele.offset().top;
myArray.push(pos);
console.log('this is still execute after resize');
$(window).on('scroll', function(){
// abcxyz
});
});
}
var target = $('p');
var run = new myFunction(target);
$(window).on('resize',function(){
console.log("resized");
$(window).off('scroll', myFunction(target));
});
答案 0 :(得分:0)
这是使用计时器进行延迟检查的一种解决方法,因为在您寻找时没有确切的调整大小事件。如果停止500毫秒,则调整函数调用的大小。这可能对您有帮助
function myFunction(ele) {
myArray = [];
this.num1 = $.each(ele, function(){
var posx = ele.offset().top;
myArray.push(pos);
console.log('this is still execute after resize');
$(window).on('scroll', function(){
// abcxyz
});
});
}
var target = $('p');
var run = new myFunction(target);
var listenForStop = (function () {
var timers = {};
return function (callback, ms, uId) {
if (timers[uId]) {
clearTimeout(timers[uId]);
}
timers[uId] = setTimeout(callback, ms);
};
})();
$(window).on('resize', function () {
listenForStop(function () {
$(window).off('scroll', myFunction(target));
}, 500, "unique");
});
答案 1 :(得分:0)
调整大小后,您只需将其覆盖为“未定义”即可。
function myFunction(ele) {
myArray = [];
this.num1 = $.each(ele, function(){
var posx = ele.offset().top;
myArray.push(pos);
console.log('this is still execute after resize');
$(window).on('scroll', function(){
// abcxyz
});
});
}
var target = $('p');
var run = new myFunction(target);
$(window).on('resize',function(){
console.log("resized");
if (typeof(myFunction) == "function"){
myFunction = undefined;
}
});
编辑:
我建议您是否需要在重用之后将原始功能用作备份。然后使用JS的“功能”,其中函数是变量。 您可以尝试以下代码:
function myFunctionBackup(ele) {
myArray = [];
this.num1 = $.each(ele, function(){
var posx = ele.offset().top;
myArray.push(pos);
console.log('this is still execute after resize');
$(window).on('scroll', function(){
// abcxyz
});
});
}
var target = $('p');
var myFunction = myFunctionBackup;
myFunction(target);
$(window).on('resize',function(){
console.log("resized");
if (typeof(myFunction) == "function"){
myFunction = undefined;
}
});
// When you want to return original simply do:
myFunction = myFunctionBackup;
答案 2 :(得分:0)
要使用.off()
函数,您必须首先使用.on()
函数实例化该事件
function myFunction(ele) {
myArray = [];
this.num1 = $.each(ele, function(){
var posx = ele.offset().top;
myArray.push(pos);
console.log('this is still execute after resize');
$(window).on('scroll', function(){
// abcxyz
});
});
}
var target = $('p');
var run = new myFunction(target);
$(function(){
$(window).on('scroll', myFunction(target));
});
$(window).on('resize',function(){
console.log("resized");
$(window).off('scroll', myFunction(target));
});