简体   繁体   English

检查类或名称而不是ID(简单代码)

[英]Check for class or name instead of ID (simple code)

I am new to jQuery and have created a little code snippet to check if any (ie one or more) of the following IDs is visible on a form. 我是jQuery的新手,并创建了一个小代码段来检查表单上是否可见以下ID(即一个或多个)。

The code works fine but I was wondering if I could achieve the same by checking for a class or name that I could assign to each ID so that it could also handle more IDs and I dont have to mention each of them separately. 该代码可以正常工作,但我想知道是否可以通过检查可以分配给每个ID的类或名称来实现相同的目的,以便它也可以处理更多ID,而我不必分别提及它们。

Can someone here help me with this and tell me how to write it properly. 这里有人可以帮助我,并告诉我如何正确编写它。

My Code (working): 我的代码(有效):

if(($('#fail1').is(':visible')) || ($('#fail2').is(':visible')) || ($('#fail3').is(':visible')))
{
    // do something;
}

This is exactly the kind of behaviour a class is meant for - duplicating logic over a set of elements. 这恰恰是类旨在实现的行为-在一组元素上复制逻辑。 It's possible to use an id attribute selector in jQuery although these are relatively slow and should be used as a last resort. 可以在jQuery中使用id属性选择器,尽管它们相对较慢,应作为最后的手段。

All you need to do is give the class to your elements and amend your code like this: 您需要做的就是将类赋予您的元素,并像这样修改您的代码:

if ($('.fail').is(':visible')) {
    alert('at least one element is visible');
}

Example fiddle 小提琴的例子

if($( "[id^='fail']" ).is(':visible') )
{
    // do something;
}

reference attribute-starts-with-selector 参考属性从选择器开始

For the record, jQuery is not required to do that: 根据记录,jQuery不需要这样做:

if (Array.prototype.some.call(document.querySelectorAll('.fail'), function (n) {
      return (window.getComputedStyle(n).display !== 'none');
    })) {
    console.log('at least one element is visible');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM