jQuery:检查是否存在具有特定类名的div [英] jQuery: Check if div with certain class name exists

查看:42
本文介绍了jQuery:检查是否存在具有特定类名的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery,我以编程方式生成了一堆div,如下所示:

Using jQuery I'm programmatically generating a bunch of div's like this:

<div class="mydivclass" id="myid1">Some Text1</div>
<div class="mydivclass" id="myid2">Some Text2</div>

在我的代码中的其他地方,我需要检测这些DIV是否存在. div的类名称相同,但每个div的ID均更改.知道如何使用jQuery检测它们吗?

Somewhere else in my code I need to detect if these DIVs exist. The class name for the divs is the same but the ID changes for each div. Any idea how to detect them using jQuery?

推荐答案

您可以通过检查从JQuery返回的第一个对象来简化此操作,如下所示:

You can simplify this by checking the first object that is returned from JQuery like so:

if ($(".mydivclass")[0]){
    // Do something if class exists
} else {
    // Do something if class does not exist
}

在这种情况下,如果第一个([0])索引处的值为真,则假定存在类.

In this case if there is a truthy value at the first ([0]) index, then assume class exists.

编辑04/10/2013 :我在此处.

这篇关于jQuery:检查是否存在具有特定类名的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆