Javascript JQuery URL事件侦听器
我试图让JQuery根据链接ID选择器高亮显示一个元素 比如说Javascript JQuery URL事件侦听器,javascript,jquery,html,events,listener,Javascript,Jquery,Html,Events,Listener,我试图让JQuery根据链接ID选择器高亮显示一个元素 比如说 突出显示下面的元素 FooIsCoolButNotBetterThenBar 我试着搜索相关的插件,但没有乐趣。有什么想法吗?那么你只想添加一个类 jQuery('a[href^=#]').click(function(){ var id = this.hash.replace('#',''); $('#' + id).addClass('isNowHighlighted'); }); 编辑: 在回答你的评
突出显示下面的元素
FooIsCoolButNotBetterThenBar
我试着搜索相关的插件,但没有乐趣。有什么想法吗?那么你只想添加一个类
jQuery('a[href^=#]').click(function(){
var id = this.hash.replace('#','');
$('#' + id).addClass('isNowHighlighted');
});
编辑: 在回答你的评论时;当页面加载时,您也可以这样做:
$(document).ready(function(){
if (window.location.hash) {
$('#' + window.location.hash.replace('#','')).addClass('isNowHighlighted');
}
});
因为#thisId不是锚,它有点毫无意义,所以我会这样做:
<a data-highlight="thisid" href="#">Goto ..</a>
$('a[data-highlight]').click(function(event){
$('#' + $(this).data('highlight')).addClass('isNowHighlighted');
event.preventDefault();
});
$('a[数据突出显示])。单击(函数(事件){
$('#'+$(this.data('highlight')).addClass('isNowHighlighted');
event.preventDefault();
});
我认为这会起作用(大多数情况下都是这样),但是如果没有点击链接怎么办。如果文档加载了/page/#thisid怎么办#thisid为什么需要成为锚定?为什么要创建无效的属性?有点突兀!它不需要是一个锚,但它没有任何意义。我认为具有显式属性更容易阅读/理解。我看不出有什么突出的地方。我将为您以一种不那么“突兀”的方式进行编辑;)相信我JimmyP女士们都喜欢
$(document).ready(function(){
if (window.location.hash) {
$('#' + window.location.hash.replace('#','')).addClass('isNowHighlighted');
}
});
<a data-highlight="thisid" href="#">Goto ..</a>
$('a[data-highlight]').click(function(event){
$('#' + $(this).data('highlight')).addClass('isNowHighlighted');
event.preventDefault();
});