2010-01-07 64 views

回答

3

嘗試這樣:

$('<ul></ul>') 
    .attr('id', 'myUL') 
    .append(
     $('<li>a</li>').click(function() { 
      alert('First one clicked'); 
     }) 
    ) 
    .append(
     $('<li>b</li>').click(function() { 
      alert('Second one clicked'); 
     }) 
    ) 
    .appendTo('body') 
; 
1
var firstLi = $('<li id='a'>a</li>'); 
firstLi.click(function() { ... }); 
$('body').append("<ul id='myUL'>").find("ul"); 
$('#myUL').append(firstLi); 
$('#myUL').append('<li id='b'>b</li>'); 
0

你就不能放在列表項一些標記,並給予他們相同的事件?或者,更好的是,使用live()事件,然後你甚至都不需要添加一個:

$('#myUL').append('<li id='a'>a</li>'); 

有:

$(function() { 
    $("#myUL li").live("click", function() { 
    if (this.id == "a") { 
     ... 
    } 
    }); 
}); 

否則只是順序顛倒和語法是好得多:

$"<li></li>").attr("id", "a").text("a").appendTo("#myUL").click(function() { 
    ... 
}); 

你可以簡單地這樣做:

$"<li id='" + a + "'>" + a + "</li>")..appendTo("#myUL").click(function() { 
    ... 
}); 

但我不建議在處理動態輸入時使用此功能,因爲您可能無法正確地轉義特殊字符,而調用attr()text()會正確轉義內容並使您不易受XSS漏洞影響。

0

試試這個

$('body').append("<ul id='myUL'>").find("ul"); 
$('#myUL').append('<li id='a' onclick="myeventHandler(event)" >a</li>'); 
$('#myUL').append('<li id='b' onclick="myeventHandler(event)" >b</li>'); 

function myeventHandler(ev){ 
     var target = ev.target || ev.srcElement; 
      alert(target.id); 
} 
相關問題