我的问题是因为我对 jQuery 几乎一无所知,并且我正在 Bootstrap 中使用分页脚本 ( http://www.bootply.com/xu9mT0pPA6 ),并且我在这一行中看到了我所理解的 $(' .pager .page_link:first').addClass('active');
将类 active 添加到之前的 anchor ,并且必须将其添加到 li 元素。
我尝试放置 $('.pager **li** .page_link:first').addClass('active');
但它不起作用。
非常感谢
编辑:代码:
var listElement = $('#pageStuff');
var perPage = 2;
var numItems = listElement.children().size();
var numPages = Math.ceil(numItems/perPage);
$('.pager').data("curr",0);
var curr = 0;
**while(numPages > curr){
$('<li><a href="#" class="page_link">'+(curr+1)+'</a></li>').appendTo('.pager');
curr++;
}
$('.pager .page_link:first').addClass('active');**
listElement.children().css('display', 'none');
listElement.children().slice(0, perPage).css('display', 'block');
$('.pager li a').click(function(){
var clickedPage = $(this).html().valueOf() - 1;
goTo(clickedPage,perPage);
});
function previous(){
var goToPage = parseInt($('.pager').data("curr")) - 1;
if($('.active').prev('.page_link').length==true){
goTo(goToPage);
}
}
function next(){
goToPage = parseInt($('.pager').data("curr")) + 1;
if($('.active_page').next('.page_link').length==true){
goTo(goToPage);
}
}
function goTo(page){
var startAt = page * perPage,
endOn = startAt + perPage;
listElement.children().css('display','none').slice(startAt, endOn).css('display','block');
$('.pager').attr("curr",page);
}
最佳答案
这个小片段添加了active
类到点击的<li>
:
//when the anchor tag is clicked
$('a.page_link').click(function(){
$('li').each(function(){
//remove all li with class active (this is to remove the previous active)
$(this).removeClass('active');
});
//add active to the parent of the clicked a tag
$(this).parent().addClass('active');
});
<强> DEMO
关于jquery - 将Class添加到特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23737872/