我有一个函数,附加<div>到一个元素点击。该函数获取所单击元素的文本,并将其赋值给名为name的变量。然后,该变量被用作附加元素的<div> id。

我需要看看是否<div> id与名称已经存在之前,我附加的元素,但我不知道如何找到这一点。

这是我的代码:

$("li.friend").live('click', function() {
  name = $(this).text();

  // if-statement checking for existence of <div> should go here
  // If <div> does not exist, then append element
    $("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");

  // Else
    alert('this record already exists');
});

这似乎很简单,但我得到的错误“意外结束的文件,而搜索类名”。我完全不知道那是什么意思。

if (document.getElementById(name)) {
  $("div#" + name).css({bottom: '30px'});
} else {
  $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}

更重要的是,我希望能够删除这个元素,如果我关闭它,然后应该从文档中删除div id [name],但.remove()不会这样做。

下面是它的代码:

$(".mini-close").live('click', function(){
  $(this).parent().remove();
});

我将.mini-close添加到append函数中,作为.labels的子函数,因此如果需要,可以关闭附加的<div>。在单击.mini-close并试图再次从li.friends中单击相同的名称后,它仍然找到div id [name]并返回if语句的第一部分。


当前回答

你可以使用jquery来检查,就像这样:

if($('#divId').length!==0){
      Your Code Here
}

其他回答

尼克的回答很准确。你也可以直接使用getElementById的返回值作为你的条件,而不是将其与null进行比较(两种方式都可以,但我个人认为这种风格更有可读性):

if (document.getElementById(name)) {
  alert('this record already exists');
} else {
  // do stuff
}

下面是我使用的jQuery函数:

function isExists(var elemId){
    return jQuery('#'+elemId).length > 0;
}

这将返回一个布尔值。如果元素存在,则返回true。 如果您想通过类名选择元素,只需将#替换为。

最简单的方法是…

if(window["myId"]){
    // ..
}

这也是HTML5规范的一部分:https://www.w3.org/TR/html5/single-page.html#accessing-other-browsing-contexts#named-access-on-the-window-object

window[name]
    Returns the indicated element or collection of elements.

把你想检查的id放在jquery的is方法中。

var idcheck = $("selector").is("#id"); 

if(idcheck){ // if the selector contains particular id

// your code if particular Id is there

}
else{
// your code if particular Id is NOT there
}

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

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):

$("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');
  }
});