jq的each函数有两种用法:
用法一:$(selector).each(), 用于遍历被选择器选中的dom。
-
用法:$(selector).each(function(index,element))
参数 | 描述 | |
function(index,element) |
|
<div class="color" title="红色的">啦啦啦</div>
<div class="color" title="绿色的">哗哗哗</div>
$(".color").each(function(index, element){
console.log(index);
console.log(element.title);
console.log(this.title); //这个this是js的对象
console.log($(this).attr("title")); //将this变成jq对象
});
// 0
// 红色的
// 红色的
// 红色的
// 1
// 绿色的
// 绿色的
// 绿色的
用法二:$.each(param, function(key, value)), 用于遍历数组或对象。
我们来根据代码效果看一下该函数的用法:
var Obj = {
"name1":"cat",
"name2":"dog"
}
//1、遍历对象:
$.each(Obj, function(key, value) {
console.log(this); //这里的this指向每次遍历中Object的当前属性值
console.log(key);
console.log(value);
});
//2、遍历数组
var arr = [ "one", "two", "three", "four"];
$.each(arr, function(index, value){
console.log(this);
console.log(index);
console.log(value);
});
jq的each函数如何进行break和continue操作?
利用$.each遍历的时候,使用break和continue关键字,发现没有用。这是因为在JQuery中没有这两条命令,可以采用以下替换方案:
return ;//实现continue功能
return false;//实现break功能
补充:js的forEach函数如何实现break和continue操作?
forEach无法实现break操作,实现continue操作是return 任何东西;
简单总结一下:
跳出循环
for => break;
$.each => return false;
forEach 没有
跳过循环
for =>continue;
$.each => return true;/return;
forEach => return /* any */;
参考文章:
https://www.cnblogs.com/zhaixr/p/7069857.html
https://blog.csdn.net/weixin_33889665/article/details/88448775