2013-06-19 31 views
0

我正在製作一個帶有關閉畫布菜單的小應用程序,其中每個項目執行特定功能。我對Google的調查顯示,jQuery的.on("click", ...比attr onclick("myFunction()")要好。該函數將從HTML文件(「存儲」在隱藏的div中)和動態數據(JSON)中加載靜態數據,並將Ajax轉換爲視口中的div。如何通過正確的方式處理jQuery?

所以這裏是我的問題:我知道有很多解決方案來實現這樣的事情,但這是一種「高效率」的方式嗎?也許這是一個愚蠢的問題,但我正在學習的進程:)非常感謝你!

HTML

<ul> 
    <li><a class="home" href="#">Home</a></li> 
    <li><a class="credits" href="#">Credits</a></li> 
</ul> 

的JavaScript(靜態數據)

$(".sidebar a").on("click", function(ev) { 
    // get class from clicked menu item 
    var sidebar_class = $(this).attr("class"); 

    // load static data from hidden div into .container 
    // e.g. .credits would load .page-credits 
    $(".container").html($(".page-"+sidebar_class).html()); 

    // hide sidebar again 
    hideSidebar(); 
}); 

回答

1

您發佈的代碼有什麼錯,其他有效的替代品:

$(".sidebar a").click(function() { //you don't ned the ev and you can use the click() method that is the same of on("click" 

$(".sidebar").on("click", "a", function() { //you have a single delegate listener for all as instead of one listener for each one. 
+0

感謝您的解釋。我認爲,由於單個委託監聽者,我正在與您的第二個替代方案一起進行。 – ohh2ahh

0

對於動態數據(與BTW靜態的作品),使用委託:

$(document).on("click",".sidebar a", function(ev) { 
    // get class from clicked menu item 
    var sidebar_class = $(this).attr("class"); 

    // load static data from hidden div into .container 
    // e.g. .credits would load .page-credits 
    $(".container").html($(".page-"+sidebar_class).html()); 

    // hide sidebar again 
    hideSidebar(); 
}); 

在這裏我使用文檔,但是ou應該使用最接近動態內容的靜態容器。

+0

感謝您的答覆。它不完全適用於我的問題,但我不知道委派,從而我學到了新東西:) – ohh2ahh