一、jQuery 的 each
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="引入相关的jQuery版本"></script>
<script>
// IE 8 不支持 高版本的jQuery ,在较低版本jQuery 2以下的时候可以运行,
// 遍历 jQuery 元素
$.each(['123', '234', '345'], function (index, item) {
console.log(item) // 123 234 345
})
</script>
</body>
</html>
- jQuery 对象的原型链中没有 forEach,对象的原型链是 Object.prototype;
- jQuery 不是专门用来遍历 jQuery 元素的, 可以在不兼容 forEach 的低版本浏览器中使用 jQuery 的 each 方法;
- 一般伪数组是对象的时候会使用jQuery的each来遍历
- $(‘div’).each(function) 一般用于遍历 jQuery 选择器选择到的伪数组实例对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script>
// 遍历body中的div元素
$('div').each(function (index, item) {
console.log(item)
})
</script>
</body>
</html>
二、ES5 的 forEach
- forEach 是 EcmaScript 5 中的一个数组遍历函数,是 JavaScript 原生支持的遍历方法 可以遍历任何可以被遍历的成员
- 由于 forEach 是 EcmaScript 5 中的,所以低版本浏览器不支持
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script>
// forEach 的 item, index 顺序和 jQuery 的正好相反
;['lutian', 'lzp', 'love'].forEach(function (item, index) {
console.log(item)
})
</script>
</body>
</html>
3.也可以用forEach 来遍历 div元素,但是利用[].slice.call($(‘div’))先将其换成数组。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script>
;[].slice.call($('div')).forEach(function (item) {console.log(item)})
</script>
</body>
</html>
三、art-template 的模板语法的 each 遍历
// 这是 art-template 模板引擎支持的语法,只能在模板字符串中使用
{{each 数组}}
<li>{{ $value }}</li>
{{/each}}
<script id="test" type="text/html">
<h1>{{title}}</h1>
<ul>
{{each list as value i}}
<li>索引 {{i + 1}} :{{value}}</li>
{{/each}}
</ul>
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/66471.html