Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

javascript - jQuery:检查是否存在具有特定类名的div(jQuery: Check if div with certain class name exists)

Using jQuery I'm programmatically generating a bunch of div 's like this:(使用jQuery,我以编程方式生成了一堆div ,如下所示:)

<div class="mydivclass" id="myid1">Some Text1</div> <div class="mydivclass" id="myid2">Some Text2</div> Somewhere else in my code I need to detect if these DIVs exist.(我需要在代码的其他位置检测这些DIV是否存在。) The class name for the divs is the same but the ID changes for each div.(div的类名称相同,但每个div的ID均更改。) Any idea how to detect them using jQuery?(知道如何使用jQuery检测它们吗?)   ask by avatar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simplify this by checking the first object that is returned from JQuery like so:(您可以通过检查从JQuery返回的第一个对象来简化此过程,如下所示:)

if ($(".mydivclass")[0]){ // Do something if class exists } else { // Do something if class does not exist } In this case if there is a truthy value at the first ( [0] ) index, then assume class exists.(在这种情况下,如果第一个( [0] )索引处有一个真值,则假定存在类。) Edit 04/10/2013: I've created a jsperf test case here .(编辑04/10/2013:我在这里创建了一个jsperf测试用例。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...