元素有多个id时匹配

use*_*426 4 javascript jquery-selectors

我正在循环浏览表单并显示与我选择的ID匹配的内容.问题是一些div包含多个id,在这种情况下它会停止工作.有任何想法吗?谢谢.

Jquery代码:

$('#myForm').find('div').each(function() {
        var myId = $(this).attr('id');

        /* This will work */
        if (myId == "Select1"){
                $(this).removeClass("hideMe");
                $(this).addClass("showMe");
                }
        /* This does not work */
        else if (myId == "Select4"){
                $(this).removeClass("hideMe");
                $(this).addClass("showMe");
                }
        else{}

        }); 
Run Code Online (Sandbox Code Playgroud)

HTML代码:

<div class="hideMe" id="Select1">
<p>Some Content</p>
</div>

<div class="hideMe" id="Select2 Select3 Select4 Select5">
<p>Some Content</p>
</div>
Run Code Online (Sandbox Code Playgroud)

Chr*_*ker 10

没有"多个ids"这样的东西.

https://developer.mozilla.org/en/XUL/Attribute/id

根据标准,id属性中的任何字符串数据都被视为值的一部分.

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

参考:http://www.w3.org/TR/REC-html40/types.html#type-name

不过还有另一种方式!您可以拥有各种类名,并且可以使用jQuery按类名获取元素.

HTML

<div class="hideMe Select1">
<p>Some Content</p>
</div>

<div class="hideMe Select2 Select3 Select4 Select5">
<p>Some Content</p>
</div>
Run Code Online (Sandbox Code Playgroud)

使用Javascript

$('.Select2')[0]
Run Code Online (Sandbox Code Playgroud)

[0]这部分是因为当你通过类名的元素,也可以是几个.jQuery选择器返回一个数组,所以你只是抓住第一个.