使用哈希将类添加到具有特定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语句(将“活动”类添加到div中的语句)按预期工作,但第三个(将“活动”类添加到链接的那个)不起作用。
有谁看到我做错了什么?
非常感谢
马库斯
没关系 – 我已经弄明白了。 我错过了我的结局’]’。
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'); }
试试这个而不是第三行:
$('#productNav li a[href='+hash+']').addClass('active');