使用散列向具有特定href的元素添加类 [英] Adding a class to an a element with a particular href using hash

查看:90
本文介绍了使用散列向具有特定href的元素添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向基于URL哈希的特定元素添加一个活动类,但它不像我期望的那样工作。



以下是我的代码:

  var hash = window.location。 hash.substr(1); 
if(hash!= false){
$('。products #copy div,#productNav li a')。removeClass('active');
$('。products #copy div#'+ hash +'')。addClass('active');
$('#productNav li a [href * =''+ hash +''')。addClass('active');
}

第二个jQuery语句(将'active'类添加到div)按预期工作,但第三个(将主动类添加到链接的那个)没有。

有人看到我做错了什么?



感谢大家
Marcus

解决方案

没关系 - 我已经明白了这一点。我错过了我的结束']'。

  var hash = window.location.hash.substr(1); 
if(hash!= false){
$('。products #copy div,#productNav li a')。removeClass('active');
$('。products #copy div#'+ hash +'')。addClass('active');
$('#productNav li a [href * =''+ hash +']')。addClass('active');
}


I'm trying to add an 'active' class to a particular element based on the URL hash but it's not working as I expect.

Here's my code:

var hash = window.location.hash.substr(1);
if(hash != false) {
    $('.products #copy div, #productNav li a').removeClass('active');
    $('.products #copy div#'+hash+'').addClass('active');
    $('#productNav li a[href*="'+hash+'"').addClass('active');
}

The second jQuery statement (the one that adds the 'active' class to the div) works as expected, but the third (the one that adds the 'active' class to the link) does not.

Anybody see anything I'm doing wrong?

Thanks much
Marcus

解决方案

Never mind - I have figured this out. I was missing my end ']'.

var hash = window.location.hash.substr(1);
if(hash != false) {
    $('.products #copy div, #productNav li a').removeClass('active');
    $('.products #copy div#'+hash+'').addClass('active');
    $('#productNav li a[href*="'+hash+'"]').addClass('active');
}

这篇关于使用散列向具有特定href的元素添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆