2010-12-18 50 views
0

我送花兒給人有,我有包含事件處理程序在我的網站多個頁面一個.js文件,像這樣的情況:如何根據頁面分離jQuery事件偵聽器?

$(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 
}); 

現在假設用戶打開的頁面example1.aspx,jQuery將搜索我的文本框1,如果發現它會附加一個點擊事件,然後將搜索我的文本框2,不會找到它,並不會附加事件。

但是像這樣的jQuery在所有情況下將在所有網頁我,TextBox2中搜索,

我想知道的是你做,以避免不必要的選擇,以獲得所謂的不想要的頁面的最佳實踐他們。

可能是2個事件不是大問題,但假設我有數百個要附加的事件,這肯定會影響頁面加載性能。

回答

7

在我們的項目中,我們總是使用基於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](); 
    } 
}); 
+0

這是我見過的最優雅,最簡單的方法之一。 – 2010-12-23 23:52:52

0

我不知道這個解決方案有多好。我只是把它當我走了。

第一個。你很可能有一些意見裝點你的JavaScript像這樣

//[all] 
$(function() { 
//[example1.aspx] 
$('#my-textbox1').click(function(){ doSomthing(); }) //--> this my-textbox1 exists in page example1.aspx 
//[/example1.aspx] 

//[example2.aspx]  
$('#my-textbox2').click(function(){ doSomthing(); }) //--> this my-textbox2 exists in page example2.aspx 
//[example2.aspx] 
}); 
//[/all] 

:獲取烏爾JS文件通過一個aspx頁面提供服務(它也可以做W/O採用這種方式 - 使用HttpHandlers的) 例如

GetJS.aspx的CodeBehind將從磁盤讀取您的實際js文件到內存中。

當時看Referer的從請求頭(這將指向已請求GetJS.aspx頁面中的值(在我們的情況下,它會要麼example1.aspx或example2.aspx)。

現在我們知道哪個頁面已經請求了JS,我們可以根據評論裝飾//[all],//[example1.aspx]等去掉它的內容,並且用適當的內容類型做一個response.writefile。

1
$(function() { 

    var pn = window.location.pathname; 

    if (/example1/.test(pn)) { 
    $('#my-textbox1').click(function(){ doSomthing(); }); 
    } 

    if (/example2/.test(pn)) { 
    $('#my-textbox2').click(function(){ doSomthing(); }); 
    } 

});