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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:19:06  来源:igfitidea点击:

jQuery: Detect if element exists

jqueryjquery-selectors

提问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

Use notand has

使用nothas

$('#listItem:not(:has(.greenCheckMark))')
    .append('<span class="greenCheckMark"></span>');

回答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 #listItemdoes not already contain a <span>with a classof greenCheckMark.

按您的要求,这样只会追加<span>在该情况下,#listItem尚不包含<span>classgreenCheckMark

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 != 0will 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").lengthwill check the entire document for green check marks).

$("#listItem span.greenCheckMark").length != 0将返回一个 JQuery 对象数组,如果该区域的长度不等于 0,则它存在。确保您专门检查要检查的位置,($("span.greenCheckMark").length将检查整个文档是否有绿色复选标记)。