The use of each() method and $.each() function in JQuery

1. The use of each() method

JQuery provides each() method to traverse the matched element information. Execute a function with each matched element as the context. Each time the passed-in function is executed, the this keyword in the function points to a different DOM element (a different matching element each time). Moreover, each time the function is executed, a numeric value (a zero-based integer) that represents the position of the element of the execution environment in the set of matched elements is passed to the function as a parameter. Returning'false' will stop the loop (just like using'break' in a normal loop). Return'true' to skip to the next loop (just like using'continue' in a normal loop).

The usage syntax is as follows:

//使用each()方法,遍历选中的复选框值
$("[name=checkItem]:checkbox:checked").each(function(index){
    alert($(this).val());
});

[Example] Use the each() method of JQuery to traverse the value of the selected check box.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JQuery中的each()方法的使用</title>
    <meta name="author" content="pan_junbiao的博客">
</head>
<body>
    <h3>请选择用户信息:</h3>
    <input type="checkbox" name="checkItem" value="1"/> pan_junbiao的博客_01<br>
    <input type="checkbox" name="checkItem" value="2"/> pan_junbiao的博客_02<br>
    <input type="checkbox" name="checkItem" value="3"/> pan_junbiao的博客_03<br>
    <input type="checkbox" name="checkItem" value="4"/> pan_junbiao的博客_04<br>
    <input type="checkbox" name="checkItem" value="5"/> pan_junbiao的博客_05<p>
    <input type="button" value="提交" id="btnSubmit"/>
</body>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
    $(document).ready(function(){
        //提交
        $("#btnSubmit").click(function()
        {
            //用户编号数组
            var idArray = new Array();

            //使用each()方法,遍历选中的用户编号
            $("[name=checkItem]:checkbox:checked").each(function(index){
                idArray.push($(this).val());
            });

            //打印结果
            console.log("您选择共:" + idArray.length + "条数据!")
            console.log(idArray);
        });
    });
</script>
</html>

Results of the:

When the submit button is clicked, the information output by the controller is as shown in the figure below:

 

2. The use of $.each() function

JQuery also provides a general traversal method $.each(), which can be used to traverse objects and arrays. The $.each() function is different from the each() method of the JQuery object. It is a global function and does not manipulate the JQuery object. Instead, it takes an array or object as the first parameter and a callback function as the second parameter. There are two parameters in the callback function: the first parameter is the index of the member or array of the object, and the second parameter is the corresponding variable or content. If you need to exit the $.each() loop, the callback function can return false, and other return values ​​will be ignored.

The usage syntax is as follows:

//使用$.each()函数,遍历数据
$.each(data,function(index,item)
{
    //忽略其他代码...
});

[Example] Call the background method to get the user list, and use JQuery's $.each() function to traverse the user list.

(1) Create a user information controller (Controller) and write a method to get the user list.

/**
 * 用户信息控制器
 * @author pan_junbiao
 **/
@Controller
@RequestMapping("user")
public class UserController
{
    /**
     * 获取用户列表
     */
    @ResponseBody
    @RequestMapping("getUserList")
    public List<UserInfo> getUserList()
    {
        //创建用户列表
        List<UserInfo> userInfoList = new ArrayList<>();
        userInfoList.add(new UserInfo(1, "pan_junbiao的博客", "您好,欢迎访问 pan_junbiao的博客"));
        userInfoList.add(new UserInfo(2, "pan_junbiao的博客", "https://blog.csdn.net/pan_junbiao"));
        userInfoList.add(new UserInfo(3, "pan_junbiao的博客", "您好,欢迎访问 pan_junbiao的博客"));
        userInfoList.add(new UserInfo(4, "pan_junbiao的博客", "https://blog.csdn.net/pan_junbiao"));
        userInfoList.add(new UserInfo(5, "pan_junbiao的博客", "您好,欢迎访问 pan_junbiao的博客"));
        //返回结果
        return userInfoList;
    }
}

(2) Create a display page (View) to display user list information.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JQuery中的$.each()函数的使用</title>
    <meta name="author" content="pan_junbiao的博客">
</head>
<body>
<input type="button" value="获取用户信息" id="btnGetUser"/>
<div id="content" style="margin-top: 10px;"></div>
</body>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
    $(document).ready(function() {
        $("#btnGetUser").click(function(){
            $.getJSON("/user/getUserList", function(data){
                $("#content").empty();

                var html = "";

                //使用$.each()函数,遍历数据
                $.each(data,function(index,item)
                {
                    html += " 索引:" + index;
                    html += " 用户编号:" + item.userId;
                    html += " 用户名称:" + item.userName;
                    html += " 博客信息:" + item.remark;
                    html += "<br>";
                });

                $("#content").html(html);
            });
        });
    });
</script>
</html>

Results of the:

 

Guess you like

Origin blog.csdn.net/pan_junbiao/article/details/107682956