2015-08-17 45 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