2013-10-24 34 views
1

我有哪些即時猜測是發生點擊事件的一些問題,因爲什麼,我點擊這裏在頁面加載後得到追加是jQuery和的jsfiddlejQuery的具有附加列表項

http://jsfiddle.net/PTHsY/

click事件問題
$(document).ready(function(){ 

// Adding a project 
$('.project-btn').click(function(e){ 
    e.preventDefault(); 

    //grab the user input for the new project 
    var project = $('.project-val').val(); 

    //Add the project to the list 
    $('<li></li>').addClass(project).appendTo('.project-list'); 
    $('<a></a>').attr("href",project).text(project).appendTo('li.'+project); 

    // create the div where the categories will go 
    $('<div></div>').attr("id",project).appendTo('.category-wrapper'); 
    // hide the div untill it is called upon 
    $('div#'+project).fadeOut(function(){ 
     $('<h1></h1>').text(project).css("text-align","center").appendTo('div#'+project); 
     // add the input for the category div 
     $('<input>').attr("type","text").addClass('category-val').appendTo('div#'+project); 
     $('<input>').attr("type","submit").attr("value","Add Category").addClass("category-btn-"+project).appendTo('div#'+project); 
     // add the ul 
     $('<ul></ul>').attr("class","category-list").appendTo('div#'+project); 
     // add the back button 
     $('<p></p>').text("back").addClass('category-back').css("cursor","pointer").appendTo('div#'+project); 
    }); 

    // clear the input search 
    $('.project-val').val(''); 

}); 

$('a').click(function(e){ 
    e.preventDefault(); 
    selectedDiv = $(this).attr("href"); 
    alert("clicked"); 
    $('.project-wrapper').fadeOut(function(){ 
     $('div#'+selectedDiv).fadeIn(); 
    }); 
}); 
}); 

我想顯示隱藏的div只有當我點擊添加列表項。由於某種原因,我說我的猜測以上它不起作用。我添加了一個「單擊」警報,以便單擊任何錨點元素時,但我無法做出響應

回答

3

您需要使用event delegation將事件分配給動態元素。 click事件添加到使用jQuery's on() methoda元素的非動態的祖先,在a選擇作爲參數傳遞(在這種情況下,我使用文檔的body):

$('body').on('click', 'a', function(e){ 
    ... 
}); 

JSFiddle Demo

當提供selector,事件處理程序被稱爲委派。當事件直接發生在綁定元素上時,不會調用該處理程序,而只會爲與選擇器匹配的後代(內部元素)調用該處理程序。 jQuery將事件從事件目標引發到處理程序所附的元素(即,最內層到最外層的元素),並沿着匹配選擇器的路徑上的任何元素運行處理程序。

+1

謝謝爲什麼我必須在動態元素上使用「on」? – swsa

+0

因爲你的元素在第一次啓動時不存在,所以我可以儘快給你支票 – swsa

+0

@swsa。您的事件處理程序未分配給任何內容,因此在您的元素動態添加時不存在。在使用'on()'時,我們將事件處理程序添加到'body'中,該元素在添加元素之前存在。 –