jQuery 尝试将 .attr({href: }) 发送到 <div id= .....> html 中同一网页的下方

问题描述 投票:0回答:1

我已经有一段时间没有使用 jQuery 了,这就是为什么我来这里问这个非常简单的问题。

因此,我动态地填充一个带有页码的分页脚本,该脚本会将用户引导至具有该特定 id 的页面。例如:

<li class="page-item current-page active"><a class="page-link" href="#">1</a></li>
<li class="page-item dots"><a class="page-link" href="#">...</a></li>

应该将用户带到网页上

<div id="1" class="page-number"><div class="number">1</div></div>

您会注意到上面的

href="#"
。我必须这样,因为文本
1
会累积到
2
等等。

所以我已经能够使用下面的代码生成所有内容:

getPageList(totalPages, currentPage, paginationSize).forEach(item =>{
       $("<li>").addClass("page-item").addClass(item ? "current-page" : "dots")
       .toggleClass("active", item === currentPage).append($("<a>").addClass("page-link")
       .attr({href: "javascript:void(0)"}).text(item || "...")).insertBefore(".next-page")

你现在会注意到我有

.attr({href: "javascript:void(0)"})
作为填充物。我知道这是错误的。我想做的是让
href
等于项目的文本。再说一次,
1
2
等等。

我尝试过的一些事情:

.attr({href: item})
.attr({href: item.this})
.attr({href: this.item})

没有任何作用。关于我做错了什么有什么想法吗?

javascript html jquery pagination
1个回答
0
投票

您需要在

#
的开头插入
href
:

.attr('href', '#' + item)

顺便说一句,当您在创建元素时初始化它的一堆属性时,我发现这种样式比所有链式方法调用更容易理解:

$("<ul>", {
    "class": `page-item ${item ? "current-page" : "dots"} ${item === currentPage ? "active" : ""}`,
    html: $("<a>", {
        href: "#" + item,
        "class": "page-link",
        text: item || "..."
    })
}).insertBefore(".next-page");
© www.soinside.com 2019 - 2024. All rights reserved.