我有我的头在一个php外部文件,链接到网站的页面。当我单击它时,它会添加活动类,但它不会保持活动状态...我不知道我做错了什么!有人能帮帮我吗?这是我的代码:
HTML ( php文件):
<ul class="site-header__list">
<li class="site-header__item">
<a class="site-header__link" href="index.php">Home</a>
</li>
<li class="site-header__item">
<a class="site-header__link" href="portfolio.php">Portfólio</a>
</li>
<li class="site-header__item">
<a class="site-header__link" href="empresa.php">Empresa</a>
</li>
<li class="site-header__item">
<a class="site-header__link" href="contactos.php">Contactos</a>
</li>
</ul>
JQUERY:
$('.site-header__item a').on('click', function() {
$(this).addClass('active');
$(this).sibling().removeClass('active');
});
发布于 2017-07-02 02:19:46
jQuery(document).on("ready page:change", function() {
if(window.location.href.indexOf("index.php") > -1 ){ //or You full URL
jQuery('.site-header__item a').addClass('active');
//or other .site-header__item a
//ps. better use id not class or add some one more unique class for every button
// as this will add class active to all '.site-header__item a'
}
});
是的,这是因为在(‘click’)事件之后,你的页面会重新加载。
发布于 2017-07-02 02:32:30
当页面根据请求的url加载时,下面的代码将相应地设置活动类:
<script type="text/javascript">
$(function() {
// Set active state on menu element
var current_url = window.location.href.split('?')[0];
var full_url = current_url + location.search;
var $navLinks = $("ul.site-header__list li a");
// First look for an exact match including the search string
var $curentPageLink = $navLinks.filter(
function() {
return $(this).attr('href') === full_url;
}
);
// If not found, look for the link that starts with the url
if (!$curentPageLink.length > 0) {
$curentPageLink = $navLinks.filter(
function() {
return $(this).attr('href').startsWith(current_url) || current_url.startsWith($(this).attr('href'));
}
);
}
// If still not found, look for links that contain the page name only
if (!$curentPageLink.length > 0) {
$curentPageLink = $navLinks.filter(
function() {
return $(this).attr('href').match(current_url) ||
current_url.match($(this).attr('href'));
}
);
}
$curentPageLink.parents('li').addClass('active');
});
</script>
我们在所有的应用程序中都使用了它,并且它工作得很好:
https://stackoverflow.com/questions/44864017
复制相似问题