为什么$("img")[0]不起作用?

run*_*run 3 jquery

码:

<img src="image1.jpg" alt="This is 1 test.">

<img src="image2.jpg" alt="This is 2 test">
Run Code Online (Sandbox Code Playgroud)

jquery代码:

 alert($('img')[0].attr('alt'));
Run Code Online (Sandbox Code Playgroud)

为什么没有弹出一个盒子,并显示 This is 1 test.

Ell*_*lle 7

您可能想要使用eq此:

 alert($('img').eq(0).attr('alt'));
Run Code Online (Sandbox Code Playgroud)


And*_*ong 7

直接回答你的问题:

它不起作用,因为[0]返回选择器的本机DOM元素,它没有调用的方法.attr().你需要使用.eq(index),它基本上提取出所index代表的元素的第th个元素$().请注意,$()返回一个类似于数组的对象而不是一个数组本身(因此[0]不能开箱即用)