Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 你如何检查选择器是否匹配jQuery中的内容? [重复](How do you check if a selector matches something in jQuery? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

In Mootools, I'd just run if ($('target')) { ... } .

(在Mootools中,我只运行if ($('target')) { ... } 。)

Does if ($('#target')) { ... } in jQuery work the same way?

(if ($('#target')) { ... } jQuery中的if ($('#target')) { ... }以相同的方式工作吗?)

  ask by One Crayon translate from so

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

1 Answer

0 votes
by (71.8m points)

As the other commenters are suggesting the most efficient way to do it seems to be:

(正如其他评论者所建议的那样,最有效的方法似乎是:)

if ($(selector).length ) {
    // Do something
}

If you absolutely must have an exists() function - which will be slower- you can do:

(如果你绝对必须有一个exists()函数 - 它会更慢 - 你可以这样做:)

jQuery.fn.exists = function(){return this.length>0;}

Then in your code you can use

(然后在你的代码中你可以使用)

if ($(selector).exists()) {
    // Do something
}

As answered here

(在这里回答)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...