如果尚未添加用户,则附加我的var

时间:2014-03-21 16:52:56

标签: jquery append

如果我的div中不存在该用户,我想在将该用户附加到我的div中之前进行检查。

// Adding the user if he has not been already added in my div
$(".ajax_panel_append").fadeIn(3000);
$(".ajax_panel_append").append("<a href='#' alt='" + user_id + "|" + user_name + "' class='chat_user'>" + user_name + "</a>");

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您现在正在添加您的用户,您可以做的一件事就是将您的用户作为javascript对象添加如下内容:

var user ={
    id: 10,
    name: "user1"
}

var user2 ={
    id: 10,
    name: "user2"
}

然后只需定义一个filter函数,我们可以在其中检查div中当前的a元素。

    var elem = $(".ajax_panel_append a").filter(function() { 
            //Also you can define here another condition filter will return the elements
            //that met your condition in this case if the element has the same text or 
           //the alt attr
            return $(this).attr("alt") == user.id+"|"+user.name;
   });

建议的功能将是这样的

function addUser(user){
    //Search for User elem will hold all the elements that match the condition
    var elem = $(".ajax_panel_append a").filter(function() { 
            return $(this).attr("alt") == user.id+"|"+user.name;
    });

   //If elem is different from 0 this means that we have elements that match the 
   //combination of userid and name so we can't add them again.
   if(elem.length == 0){
      //Add the new element
      $(".ajax_panel_append").append("<a href='#' alt='" + user.id + "|" + user.name + "'    class='chat_user'>" + user.name + "</a>"); 
    }

}

Fiddle example