jQuery 如何使用JQuery查找页面上存在的特定类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7387160/
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 23:46:33  来源:igfitidea点击:

How to find particular class exists on a page using JQuery

jquery

提问by Manoj Singh

I want to write JQuery which will find whether Class="Mandatory"exists on the page and if any element is having this class then only perform certain action.

我想编写 JQuery,它将查找页面上是否存在Class="Mandatory",如果有任何元素具有此类,则只执行某些操作。

Thanks

谢谢

回答by peirix

Just check how many elements you hit, when you search for it with jQuery

当您使用 jQuery 搜索时,只需检查您命中了多少个元素

if ($(".Mandatory").length > 0) {
    // Do stuff with $(".Mandatory")
    $(".Mandatory").each(function() {
        // "this" points to current item in looping through all elements with
        // class="Mandatory"
        $(this).doSomejQueryWithElement();
    }); 
}

EDITIf you wanna do that check for your submit button click, just do that check after the click:

编辑如果你想对你的提交按钮点击进行检查,只需在点击后进行检查:

$("input[type='submit']").click(function() {
    if ($(".Mandatory").length > 0) {
        // Do some code here
    }
});

回答by Russell

If you want to only do the action once, you could use:

如果您只想执行一次操作,可以使用:

if ($('.Mandatory').length > 0) {
  //do your thing
}

Otherwise if you want to do it for each Mandatoryelement:

否则,如果您想为每个Mandatory元素执行此操作:

$('.Mandatory').each(function(){
  //do your thing
});

回答by samir chauhan

The best way to do this is search class within the body tag.

最好的方法是在 body 标签中搜索类。

$('body').find('.Mandatory').length;

回答by Anpher

Basic jQuery (CSS) selector by class.

按类的基本 jQuery (CSS) 选择器。

if($(".Mandatory").length)

回答by Luke Madhanga

I'd go about it like so:

我会这样做:

$('*').hasClass('mandatory') ? "what to do if true" : "what to do if false"

$('*').hasClass('mandatory') ? "what to do if true" : "what to do if false"

I find ternary conditions more useful as you can set variables more quickly

我发现三元条件更有用,因为您可以更快地设置变量

回答by Gowri

using hasClass()you can find

使用hasClass()你可以找到