2017-01-23 21 views
-3

我在jQuery中编写了多个函数。您的javaScript中的冗余事件

我的客户说,你的JavaScript目前有多余的事件。请合并所有应在单个事件中发生的代码。

我还在学习jQuery。请帮忙。

谢谢。

'use strict'; 
 

 
$(function() { 
 
\t $('.task-list').on('click', 'li.list', function() { 
 
\t \t $(this).toggleClass('completed'); 
 
\t }); 
 
}); 
 

 
$(function() { 
 
\t setTimeout(function(){ 
 
\t \t $('body').addClass('loaded'); 
 
\t }, 3000); 
 
}); 
 

 
$(function() { 
 
\t $('[data-toggle="tooltip"]').tooltip(); 
 
\t $('[data-toggle="popover"]').popover(); 
 
}); 
 

 
$(function(){ 
 
\t $('.nav li.dropdown').hover(function() { 
 
\t \t $(this).addClass('open'); 
 
\t }, function() { 
 
\t \t $(this).removeClass('open'); 
 
\t }); 
 
});

+0

不要忘了接受一个答案,如果它是你不够清楚,或在评论询问详情 –

回答

2

我想你应该绑定document.ready事件中的所有事件。

由于对jQuery的官方网站saild:

一个页面不能安全,直到该文件是操纵“准备好了。” jQuery为你检测到这种状态。包含在 $(document).ready()中的代码只会在页面Document Object 模型(DOM)准备好执行JavaScript代码时运行。

所以做这样的事情:

$(document).ready(function() { 
    //your code goes here 
    //bind the all events and do other stuff 
}); 

or 

$(function(){ 
    //your code goes here 
    //bind the all events and do other stuff 
}); 

多次,不要重蹈覆辙。

+0

'$(函数(){})'是一回事...自己更彻底地阅读文档 – charlietfl

+0

是的,同样的事情。但是你不需要一次又一次地使用它。 –

+0

这与你的回答有什么关系?答案仍然误导 – charlietfl

2

尝试:

'use strict'; 

$(function() { 
    $('.task-list').on('click', 'li.list', function() { 
     $(this).toggleClass('completed'); 
    }); 

    setTimeout(function(){ 
     $('body').addClass('loaded'); 
    }, 3000); 

    $('[data-toggle="tooltip"]').tooltip(); 
    $('[data-toggle="popover"]').popover(); 

    $('.nav li.dropdown').hover(function() { 
     $(this).addClass('open'); 
    }, function() { 
     $(this).removeClass('open'); 
    }); 
}); 

$(function() {...})您使用的是实际上是一个短手$(document).ready(function() {...})。此方法允许您在应用jQuery之前检查文档是否已完全加载。对每个代码块执行此操作意味着每次添加新的监听器时,这都不是您想要的。更多关于多次调用此功能here

查看更多有关此功能上JQuery documentation