首页 > 解决方案 > Javascript to highlight current page

问题描述

New javascript user here... thanks in advance for any help. I am adding pagination to a news site so only 10 articles show on page 1 and you have to select 2, 3, 4, etc. to see more articles. The code I have allows me to go to page 2, 3, etc., but it is not highlighting my active page for some reason.

Here is the code I have:

HTML:

<table class="news-pages" id="paginator">
 <tr>
   <% for(var i = 1; i <= num_pages; i++) { %>
     <td class="news-pages-option"><%-i%></td>
   <% } %>
  </tr>
</table>

JS:

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
      results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

const page = getParameterByName('p');
$('.news-pages-option').parent().addClass('active');

CSS:

.news-pages-option.active {
  background-color: #cccccc;
  border: none;
  padding: 3px 8px 3px 8px;
  text-decoration: underline;
}

标签: javascriptpagination

解决方案


看起来您想突出显示与从 url 中提取的页面变量相对应的选项卡。尝试:

const page = getParameterByName('p') - 1; // the array of tabs is zero-based so subtract one
$('.news-pages-option:eq(' + page + ')').addClass('active');

推荐阅读