Amr*_*rhy 0 asp.net jquery javascript-events
我总是有一个案例,我有一个.js文件,其中包含我网站上许多页面的事件处理程序,如下所示:
$(function () {
$('#my-textbox1').click(function(){ doSomthing(); }) //--> this my-textbox1 exists in page example1.aspx
$('#my-textbox2').click(function(){ doSomthing(); }) //--> this my-textbox2 exists in page example2.aspx
});
Run Code Online (Sandbox Code Playgroud)
现在假设用户打开了页面example1.aspx,jquery将搜索my-textbox1,如果发现它将附加一个click事件,然后将搜索my-textbox2并且找不到它并且不会附加事件.
但是像这样的jquery在所有情况下都会在所有页面中搜索my-textbox2,
我想知道的是你做的最好的做法是避免在不需要它们的页面中调用不需要的选择器.
可能它不是2个事件的大问题,但假设我有数百个事件想要附加,这肯定会影响页面加载性能.
在我们的项目中,我们总是使用基于body类的视图模式.这是一个规定的示例:
views = {
home: function() {
// do stuff on home page
},
products: function() {
// do other stuff on products page
}
};
$.each(document.body.className.split(' '), function() {
if (this in views) {
views[this]();
}
});
Run Code Online (Sandbox Code Playgroud)