2012-08-09 109 views
5

我嘗試新的元素添加到有序列表與鏈接,它的去除:添加事件處理程序,以新創建的元素

$('#list ol').append('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>'); 

,但是這是行不通的:

$('a[href^="#remove"]').on('click', function(event){ 
    alert('Removing: '+$(this).attr('href').substr(8)); 
    event.preventDefault(); 
}); 

知道爲什麼?

回答

8

將jQuery標籤中的新元素換行並在當時應用事件處理程序。這比使用比較複雜的jQuery選擇的元素已經被插入到DOM後,事件處理函數分配一個更清潔,更有效的方法:

//this line will create your element in memory, but not insert it to the DOM 
var newElmt = $('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>'); 

//you can apply jQuery style event handlers at this point 
newElmt.on('click',function(e) { 

    alert('Removing: '+$(this).attr('href').substr(8)); 
    event.preventDefault(); 
}); 

//insert the element as you were before 
$('#list ol').append(newElmt); 
0
$('#list').on('click', 'a[href^="#remove"]', function(event){ 
    alert('Removing: '+$(this).attr('href').substr(8)); 
    event.preventDefault(); 
}); 

當你追加li動態,所以您需要使用.on()作爲委託處理程序來委託事件處理。

相關問題