javascript - 单击()获取类名

标签 javascript jquery ajax json onclick

更新:评论者告诉我更改一些代码,这是新代码,它也不起作用。

我正在创建类似 Facebook 的聊天。它从 JSON 文件获取最新消息“未读”,并将文本通过“LI”附加到框中的“UL”元素。如果该框不存在,它将创建并附加文本。我希望当我单击该 div 时,它会使用 margin-bottom 负数隐藏,当我再次单击它时,它会显示为 Margin-Bottom:0。请帮助我,因为它不起作用。

function showChat(id){
$(this).animate({marginBottom : "0"}).removeClass("hidden_box").addClass("active_box").removeAttr('onclick').click(function(){
       hideChat(Id);
    });

}
function hideChat(id){
$(this).animate({marginBottom : "-270px"}).removeClass("active_box").addClass("hidden_box").click(function(){
       showChat(Id);
    });

}

function getOnJSON(){

//Creating Variables that will be used
var from;var to;var msg_id;var msg_txt;

//Getting the data from the json file
$.getJSON("/ajax/chat.json.php",function(data){

//Repeat for each result
$.each(data.notif, function(i,data){

//Getting a var to info
from = data.from;to = data.to;msg_id = data.id;msg_txt = data.text;

//check if div exists
        if ($("#chat_"+from+"_lp").length === 0){

//If not, create the div
            $("#boxes").append('<div id="chat_'+from+'_lp" class="chat_box hidden_box clickable_box"></div>');

//Add the senders name
            $("#chat_"+from+"_lp").append('<div id="'chat_+from+'_nick" class="chat_name">'+from+'</div>');

//Add the chats UL
            $("#chat_"+from+"_lp").append('<ul id="chat_'+from+'_txt" class="chat_txt"></ul>');

//Add the message text
            $("#chat_"+from+"_lp").append('<li id="' + msg_id + '">'+ msg_txt+'</li>');

//Add event handler for each div
            $('#chat_'+from+'_lp').click(function() {showChat(this);});

//If div exists just add the text
        }else{

//Add the message text
            $("#chat_"+from+"_txt").append('<li id="' + msg_id + '">'+ msg_txt+'</li>');

//Add event handler for each document
            $('#chat_'+from+'_lp').click(function() {showChat(this);});

//Close If
        }
//Close data for each item      
    });

//Close JSON
});

//Close Function
}

更新 2:为了停止创建和追加内容,我制作了一个将要追加的唯一 HTML 字符串。

new_chat_string = '<div id="chat_'+from+'_lp" class="chat_box hidden_box clickable_box"><div id="'chat_+from+'_nick" class="chat_name">'+from+'</div><ul id="chat_'+from+'_txt" class="chat_txt"><li id="' + msg_id + '">'+ msg_txt+'</li></ul></div>';

$("#boxes").append(new_chat_string);    

最佳答案

使用类而不是id

<div id="chat_sender_lp" class="chat_box hidden_box clickable_box sender-click"

然后

$('.hidden_box.sender-click').live('click', function(){
   $(this).slideToggle(500);
});

关于javascript - 单击()获取类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9241928/

相关文章:

javascript - 使用 JXA 访问对象的属性

php - MySQL - 比较来自 Ajax 数组的值,如果不在表中则删除它们

javascript - AJAX自定义错误处理代码问题

javascript - Promise 未解析且未返回预期值 :

javascript - 如何使用 JavaScript 单击 Flash 对象?

javascript - 在一个时间间隔内更改 CircleGeometry 对象一侧的纹理/图像

jquery - 如何使某些日期在 html 日期表单中不可用

javascript - 无法从 HTML 获取表值

php - 如何将很长的字符串从一页传递到另一页?

javascript - Jquery ajax 从请求的 php 页面不返回任何内容