jQuery $('img[alt]') 与 $('img').attr('alt')?

jQuery $('img[alt]') vs. $('img').attr('alt')?

我的问题分两部分。 只是我一直想知道的事情。

1) 使用有什么区别:

$('img[alt]').get(-1); // ignore the .get

$('img').attr('alt').get(-1); // ignore the .get

第一个选项是访问图像 alt 属性的有效方法吗?或者只有第二个有效?

和 2) 在 .get 请求中将数字(负数或非负数)作为参数是否有效?我肯定不是,但我想确定...谢谢!

它们是不同的。第一个选项没有获得 alt 属性,而第二个选项有。

  • $('img[alt]') - select 或 img[alt] 将 select 一个具有 alt 属性的 img 元素。值得一提的是 [alt] 是一个 attribute selector.

    换句话说,基于select或img[alt]:

    <!-- This img element would be selected because it *has* an 'alt' attribute. -->
    <img src="../" alt="Alt attribute" />
    
    <!-- This img element would NOT be selected. -->
    <img src="../" />
    
  • $('img').attr('alt') - .attr() method 将获取或设置 selected 元素的属性。所以在这种情况下,$('img').attr('alt') 检索 img 元素的 alt 属性。


.get() method 将检索与 jQuery select 或匹配的 DOM 元素。此方法接受的唯一参数是您要获取的元素的索引。此参数是可选的,-1 的索引不会 return 元素。


附带说明一下,您不能将 .get() 方法 链接到 .attr() 方法 之后。