2014-05-08 41 views
1

我用靜態用戶製作聊天應用程序。並點擊該用戶,它會打開一個聊天室。但該聊天室上的關閉按鈕不起作用。聊天框頭上的關閉按鈕不起作用

我正在使用jQuery來實現這一點。

$(document).ready(function() { 
    $('a').click(function(e) { 
    e.preventDefault(); 
    var targetUser = ($(this).html()); 
    $(document).data('chat.targetUser', targetUser); 
    var user = '<div class="user open" id="' + targetUser + '"><header><div class="status"></div><div class="header-text">' + targetUser + '</div><div class="close">&times;</div></header><div class="message-area"></div><div class="input-area"><input type="text" id="input" /></div></div>'; 
    $('#chat').append(user); 
    $('#chat').find(".close").click(function() { 
     $(this).closest(".user open").hide(); 
    }); 
    }); 
}); 
+0

動態添加聊天室嗎? – anna

+0

對於在domready之後創建的元素上的綁定事件,使用'$('#item')。on('click',function(){/ * callback * /});' –

+0

yes alig..chatbox opened when click on用戶從用戶列表中。 – Reetika

回答

0

console.log($('#chat').find(".close"));,以找出是否選擇工作

$("#chat .close").on("click", function() { 
    $(this).closest(".user open").hide(); 
}); 
+0

它的工作,但所有聊天框隱藏,而不是一個。 – Reetika

5

當你在運行時追加元素DOM,你一定要試試這裏event delegation

$('#chat').on("click",".close",function(){ 
     $(this).closest(".user open").hide(); 
}); 

事件委託允許我們將一個事件監聽器附加到一個父元素,該元素將爲匹配選擇器的所有後代觸發,whe那些現在存在的或後來增加的後代。

0

嘗試以下代碼: -

$('#chat').on("click", ".close" , function(){ 
      $(this).closest(".user open").hide(); 
     }); 

更多信息: -

https://learn.jquery.com/events/event-delegation/

事件代理是指使用事件傳播 (鼓泡)來處理的過程中DOM中的事件比事件原來的 元素更高inated。它允許我們爲現在或將來存在的元素附加一個單一的事件監聽器。