元素有多个id时匹配

时间:2011-06-15 21:17:59

标签: 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{}

        }); 

HTML代码:

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

<div class="hideMe" id="Select2 Select3 Select4 Select5">
<p>Some Content</p>
</div>

5 个答案:

答案 0 :(得分: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>

<强>的Javascript

$('.Select2')[0]

[0]部分是因为当您按类名获取元素时,可以为几个。 jQuery选择器返回一个数组,所以你只是抓住第一个数组。

答案 1 :(得分:1)

您不能拥有多个ID。但是,如果您愿意,可以有多个班级。

答案 2 :(得分:1)

拥有多个ID是无效的 - 浏览器会看到id =“Select2 Select3 Select4 Select5”作为单个字符串,但该字符串将无效,因为它包含空格。

来自HTML数据类型规范:http://www.w3.org/TR/REC-html40/types.html#type-name

我认为你应该使用类。

答案 3 :(得分:0)

ID 唯一 ,元素只能 1 ID

改为使用多个类。

答案 4 :(得分:0)

一个元素不应该有多个唯一标识符,这就是为什么它实际上被称为id:来识别它与其他所有标识符。无论如何,你必须测试myId是否包含Select4而不是测试相等性。