1.$(selector).each(function(index,element))方法
通过jquery的选择器往往可以获取多个对象,each() 用于遍历这些对象。
函数原型:
$(selector).each(function(index,element))
html使用代码举例(点击按钮打印索引和元素):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.5.0/jquery.js"></script>
<script>
$(function () {
$("#sendBtn").click(function () {
$(".addressInput").each(function (index, element) {
console.info(index);
console.info(element);
});
});
})
</script>
</head>
<body>
<label>
发送邮箱名1:
<input class="addressInput" type="text">
</label>
<label>
发送邮箱名2:
<input class="addressInput" type="text">
</label>
<label>
发送邮箱名3:
<input class="addressInput" type="text">
</label>
<button id="sendBtn" >批量发送邮件</button>
</body>
</html>
注意:each() 方法为每个匹配元素规定要运行的函数。
提示:返回 false 可用于及早停止循环。
- 使用return true,相当于 continue,跳出本次循环
- 使用return false,相当于 break,直接跳出当前循环
所以若在.click方法中使用each且在each函数中使用return是无法正常退出click函数的,只能使用一个标志变量如flag来先遍历再用if语句进行判断,然后return直接退出click方法
参考https://www.w3school.com.cn/jquery/traversing_each.asp
2.$.each() 方法;
遍历数组元素
$(function () {
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
})
其可以:
-
遍历对象: 遍历对象属性。
-
遍历数组:对数组进行遍历,并同时显示关键字及数值。
-
遍历数组:遍历一个数组,并同时访问迭代的元素及它的索引值。
-
遍历一个元素:在一个元素的属性上进行遍历,并同时访问它的关键词及值。