You can use .length
after the selector to see if it matched any elements, like this:(您可以在选择器后面使用.length
来查看它是否与任何元素匹配,如下所示:)
if($("#" + name).length == 0) {
//it doesn't exist
}
The full version:(完整版:)
$("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');
}
});
Or, the non-jQuery version for this part (since it's an ID):(或者,这部分的非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');
}
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…