1. 程式人生 > >利用js動態新增標籤,並且使用點選效果為其新增和移除class

利用js動態新增標籤,並且使用點選效果為其新增和移除class

js檔案

$(function () {
    $.ajax({
        type: "post",
        url: purl+"/news/categorys",
        datatype: "json",
        success: function (data) {
            var datalist = data.data;
            if (datalist == undefined || datalist.length < 1) return;
            var navid = datalist[1].id;
            $.ajax({
                type: "post",
                url: purl+"/news/find?categoryId=" + navid + "&pageNo=1",
                success: function (data) {
                    // var newslist = data.data.newsList;
                    // newsload(newslist);
                }
            })
            for (var i = 1; i < datalist.length; i++) {
                html = `<li  id = ` + datalist[i].id + `>
                    <a href="#">`+ datalist[i].name + `</a>
                </li>`;
                $("#newslist-title").append(html);
                // 給新聞導航條增加樣式
                var listTab = $(".nav-list>li");
                var listTabfirst = $(".nav-list>li:first-child");
                listTabfirst.addClass("active")
                $(".nav-list").on("click", "li", function () {
                    var index = $(this).index();
                    for (var i = 0; i < listTab.length; ++i) {
                        $(listTab[i]).removeClass("active");
                    }
                    $(listTab[index]).addClass("active");
                })
            }
            onClickNewsListCategory(navid);
        }
    })
})

html:
<div class="col-xs-12 " id="new-naver">
                        <ul class="nav-list" id="newslist-title">
                           <!-- 動態生成新聞列表導航 -->
                        </ul>
                    </div>