jQuery:检测元素是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3365181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Detect if element exists
提问by st4ck0v3rfl0w
In my code I have the following html that gets appended to a List Item when the user clicks on a specific element.
在我的代码中,当用户单击特定元素时,我将以下 html 附加到列表项。
<span class="greenCheckMark"></span>
Using jQuery, how would I detect if the element existed, and if so, not add another green checkmark?
使用 jQuery,我如何检测元素是否存在,如果存在,不添加另一个绿色复选标记?
$('.clickedElement').live('click',function(){
//does the green check mark exist? if so then do nothing, else
$('#listItem).append('<span class="greenCheckMark"></span>');
});
回答by Adam
回答by TJ Koblentz
You could just look for it?
你就随便找找?
($('.greenCheckMark', '#listItem').length > 0) ? /* found green check mark in #listItem */ : /* not found */ ;
EDIT: Fixed 'un-relatedness' to question.
编辑:修复了问题的“不相关性”。
回答by James
As per your requirements, this will only append the <span>
in the case that #listItem
does not already contain a <span>
with a class
of greenCheckMark
.
按您的要求,这样只会追加<span>
在该情况下,#listItem
尚不包含<span>
了class
的greenCheckMark
。
var listItem = $('#listItem');
if ( !listItem.find('span.greenCheckMark')[0] ) {
listItem.append('<span class="greenCheckMark"></span>');
}
回答by Alex Larzelere
$('.clickedElement').live('click',function(){
//does the green check mark exist? if so then do nothing, else
if($("#listItem span.greenCheckMark").length != 0)
{
$('#listItem').append('<span class="greenCheckMark"></span>');
}
});
Okay, after a few edits, this should be what you're looking for.
好的,经过几次编辑后,这应该就是您要查找的内容。
$("#listItem span.greenCheckMark").length != 0
will return an array of JQuery objects, if that area has a length not equal to 0 then it exists. Make sure that you are checking specifically for where you want to check, ($("span.greenCheckMark").length
will check the entire document for green check marks).
$("#listItem span.greenCheckMark").length != 0
将返回一个 JQuery 对象数组,如果该区域的长度不等于 0,则它存在。确保您专门检查要检查的位置,($("span.greenCheckMark").length
将检查整个文档是否有绿色复选标记)。