且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何找到jQuery中是否存在具有特定id的div?

更新时间:2023-11-29 13:07:46

您可以使用 .length 在选择器后查看它是否与任何元素匹配,如下所示:

You can use .length after the selector to see if it matched any elements, like this:

if($("#" + name).length == 0) {
  //it doesn't exist
}

完整版:

$("li.friend").live('click', function(){
  name = $(this).text();
  if($("#" + name).length == 0) {
    $("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
  } else {
    alert('this record already exists');
  }
});

或者,这部分的非jQuery版本(因为它是一个ID):

Or, the non-jQuery version for this part (since it's an ID):

$("li.friend").live('click', function(){
  name = $(this).text();
  if(document.getElementById(name) == null) {
    $("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
  } else {
    alert('this record already exists');
  }
});