each()
each(callback)
意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。而且,在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数(从零开始的整形)。
返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element.
Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index).
Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).返回值
jQuery
参数
callback (Function) : 对于每个匹配的元素所要执行的函数
示例
迭代两个图像,并设置它们的 src 属性。注意:此处 this 指代的是 DOM 对象而非 jQuery 对象。
HTML 代码:
jQuery 代码:
结果:
如果你想得到 jQuery对象,可以使用 $(this) 函数。
jQuery 代码:
你可以使用 'return' 来提前跳出 each() 循环。
HTML 代码:
jQuery 代码:
size()
返回值
Number
示例
计算文档中所有图片数量
HTML 代码:
jQuery 代码:
结果:
length
返回值
Number
示例
计算文档中所有图片数量
HTML 代码:
jQuery 代码:
结果:
get()
取得所有匹配的 DOM 元素集合。
这是取得所有匹配元素的一种向后兼容的方式(不同于jQuery对象,而实际上是元素数组)。
如果你想要直接操作 DOM 对象而不是 jQuery 对象,这个函数非常有用。
返回值
Array<Element>
示例
选择文档中所有图像作为元素数组,并用数组内建的 reverse 方法将数组反向。
HTML 代码:
jQuery 代码:
结果:
get(index)
返回值
Element
参数
index (Number) :取得第 index 个位置上的元素
示例
HTML 代码:
jQuery 代码:
结果:
index(subject)
返回值
Number
参数
subject (Element) : 要搜索的对象
示例
返回ID值为foobar的元素的索引值值。
HTML 代码:
jQuery 代码:
结果:
5