从 getElements 中选择元素

Selecting element from getElements

我有这样的 DOM 结构:

<article class="detail">
  <img src="img1.jpg" />
  <img src="img2.jpg" />
  <img src="img3.jpg" />
</article>

如果我 select 使用

immagini = $$('article.detail').getElements('img')
console.log(immagini[0]) // returns Object { 0: <img>, 1: <img>, 2: <img> }

如果我 select 使用

immagini = $$('article.detail img')
console.log(immagini[0]) // returns <img src="img1.jpg" />

我无法理解其中的区别,因为正如文档所说:

getElements collects all descendant elements whose tag name matches the tag provided. Returns: (array) An Elements array of all matched Elements.

感谢任何解释

当您使用 $$ 时,您会得到一个类似数组的 article.detail 元素集合。因此 对于每个 找到的元素 getElements 将获得所有 img

这意味着 映射 原始文章类数组集合到 getElements 发现的数组中。

检查这个例子:

<article class="detail" id="foo">
    <img src="img1.jpg" />
    <img src="img2.jpg" />
    <img src="img3.jpg" />
</article>
<article class="detail" id="bar">
    <img src="img1.jpg" />
    <img src="img2.jpg" />
    <img src="img3.jpg" />
</article>

和 JS/MooTools:

var articles = $$('article.detail')
var img = articles.getElements('img')
console.log(articles, img);

这将打印:

[article#foo.detail, article#bar.detail], [Elements.Elements[3], Elements.Elements[3]]

jsFiddle: http://jsfiddle.net/akcvx8gL/

如果你只想要一个包含所有 img 元素的数组,你可以像你在其他示例中建议的那样在 $$ 中使用整个选择器 'article.detail img' 或最后使用 .flatten()jsFiddle).

关于这个有一个related blog post

"All the methods that MooTools adds to the Element native are added to the Elements class as well. You can do some pretty nifty chaining because of this. This is because any method you call on Elements, will loop through the array and try to call the method on each individual element [...] will return an array of the values from each element.".