2012-02-18 53 views
0

這就是我想要做的jQuery的:使用.append添加代碼,並使其在工作。每個jQuery中

<ul> 
    <li> <a href="#" alt="1"> User1 </a> 
    <li> <a href="#" alt="2"> User2 </a> 
</ul> 

<div id="chat_rooms"> 

    <div id='pvt0' class='pvtroom' page='room.php?id=0'><span>Chating With Default</span> 
     Here Is chat words 
</div> 

</div> 

我讓它當UL讓聊天室用戶點擊在#chat_rooms 附加使用此代碼

$('ul li a').live("click",function(){ 
     var uid = $(this).attr("alt"); 
     var uname = $(this).text(); 
     $("#chat_rooms").append("<div id='pvt"+uid+"' class='pvtroom' page='room.php?id="+uid+"'> <span> Chating With "+ uname`enter code here` +" </span> </div>"); 
}); 

,我有這個功能已經工作

$('.pvtroom').each(function(){ 
     // my ajax request to room here 
     $(this).css("border","1px solid #f00"); 
    }); 

這是我的問題 如果我點擊用戶與他聊天,我的房間將apper,但不會採取每個作爲默認房間的效果 我想如果用戶點擊任何房間房間工作直接與每個請求,並得到結果數據庫

回答

1

您不能使代碼運行時each中的代碼適用於尚不存在的元素。

把這些代碼的功能,讓你可以重複使用它:

function initChatRoom(room) { 
    // my ajax request to room here 
    room.css("border","1px solid #f00"); 
} 

$('.pvtroom').each(function(){ 
    initChatRoom($(this)); 
}); 

現在使用它時,你增加一個房間:

$('ul li a').live("click",function(){ 
    var uid = $(this).attr("alt"); 
    var uname = $(this).text(); 
    var room = 
    $("<div/>", { id: 'pvt'+uid, 'class': 'pvtroom', page: 'room.php?id='+uid }) 
    .append($("<span/>").text('Chatting With '+ uname)); 
    $("#chat_rooms").append(room); 
    initChatRoom(room); 
}); 
相關問題