2015-08-17 49 views
4

我发现我写了一个程序中的错误,但错误的行为莫名其妙对我说:jQuery的EQ功能意外行为

如果我有:

<input type="text" name="cust_id" value="666" /> 
<input type="text" name="phone[]" value="666" /> 

然后使用这个选择:

var test = $("input[name=phone[]]:eq(0)"); 
test.css("color", "red"); 

我看到这一点:

enter image description here

我很惊讶的是,eq(0)选择,即使我明确告诉它找到唯一与name=phone[]

在这里先输入的事实是一个小提琴:https://jsfiddle.net/1xdnv1t8/

这是预期的行为? eq选择器是否忽略属性选择器?

回答

4

使用

var test = $("input[name='phone[]']:eq(0)"); 

JSFiddle

selector especification状态

jQuery("[attribute='value']")

attribute: An attribute name.

value: An attribute value. Can be either an unquoted single word or a quoted string.

+3

链接到选择文档,并解释你改变了什么可能是有用的。 – ssube

+3

记得花些时间和*解释为什么你的答案可以解决问题。* –

+0

啊,报价是必需的? – dgig

3

你缺少的属性值引号包围。试试这个 -

var test = $('input[name="phone[]"]:eq(0)');

1

的方括号在选择混淆属性选择部分,因为它没有加引号。

$("input[name=phone]:eq(0)") 

或者,用引号括属性选择:

$("input[name='phone']:eq(0)") 
5

需要引用name属性:

var test = $("input[name='phone[]']:eq(0)"); 
如果您更改名称的第二个输入到 phone那么 works as expected通知

因为phone[]不是有效的名称不带引号。所以jQuery解析器(或DOM)完全忽略了一切无效,并将选择器视为仅仅是input[name='phone']:eq(0)。另外值得注意的是,这看起来像这个行为是固定在更新版本的jQuery。你在演示中使用了相当老的1.6.4,但是如果你使用1.8.x或更高版本检查它,它将正确地运行错误。

例如,如果你试图

try { 
 
    document.querySelector("input[name=phone[]]") 
 
} 
 
catch(e) { 
 
    alert(e.message) 
 
}

它甚至会引发错误

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': 'input[name=phone[]]' is not a valid selector.

但jQuery是更宽容,它只是选择一切所能。

+1

根据我认为解析器忽略无效选择器而不是将其视为'name ='phone''。否则我不明白为什么会选择第一个'input'元素:'input:eq(0)'或'input [name]',或许。 –

+0

感谢您的彻底解答,非常有帮助。 – dgig

1

尽管引用name属性的值并非严格要求(大多数情况下,jQuery在没有它们的情况下都可以正常工作),正如您注意到的,当涉及非字母数字字符并且jQuery将它们解释为CSS符号。

的解决方案是始终正确逃避这些字符(:.[]等)作为jQuery的建议,以两个反斜杠:

In order to tell jQuery to treat these characters literally rather than as CSS notation, they must be "escaped" by placing two backslashes in front of them.

所以根据jQuery的文档,你应该使用var test = $("input[name='phone\\[\\]']:eq(0)");作为选择器(尽管简单地正确地引用您的案例中的字符串也可以正常工作)。

jsFiddle example

编号:How do I select an element by an ID that has characters used in CSS notation?

+0

感谢您提供特殊字符的列表,非常有帮助。 – dgig