jQuery加载更多

作者: 辉夜乀 | 来源:发表于2017-05-01 07:43 被阅读45次

Github地址

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        ul,
        li {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        #news>li {
            width: 600px;
            border: 1px solid #000080;
            border-radius: 5px;
            font-size: 1.25rem;
            margin: 0 auto;
            text-align: center;
            padding: 5px;
            margin-top: 10px;
        }
        .btn {
            width: 200px;
            display: block;
            margin: 0 auto;
            margin-top: 20px;
            font-size: 1.5rem;
            padding: 10px;
            background: #AFEEEE;
        }
    </style>
</head>
<body>
    <ul id="news">
        <!-- <li>新闻1</li>
        <li>新闻2</li>
        <li>新闻3</li>
        <li>新闻4</li>
        <li>新闻5</li> -->
    </ul>
    <button id="more" class="btn">加载更多</button>

    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script>
        var $news = $("#news")
        var $btn = $("#more")
        var $len = 3;
        var lock = true
        $btn.on("click", function(){
            if(!lock){
                return
            }
            lock = false;
            var $index = $news.children("li").length;
            $.ajax({
                url: "/loadMore",
                type: "get",
                data: {
                    len: $len,
                    index: $index
                }
            }).done(function(ret){
                //appendHtml(ret)
                console.log("done...");
                console.log(ret)
                appendHtml(ret)
                lock = true
            }).fail(function(){
                console.log("服务器异常")
            })
        })
        function appendHtml(news){
            for(var i=0; i<news.length; i++){
                var $newsList = $("<li>"+news[i]+"</li>")
                $news.append($newsList)
            }
        }
    </script>
</body>
</html>

后端router.js

app.get("/loadMore", function(req, res){
    var len = req.query.len
    var index = req.query.index
    var news = []
    for(var i=0; i<len; i++){
        news[i] =  "新闻" + (parseInt(index)+i+1)
    }
    res.send(news)
})

相关文章

网友评论

    本文标题:jQuery加载更多

    本文链接:https://www.haomeiwen.com/subject/dfdftxtx.html