如果我有这样的div,我如何通过jquery选择当前链接:
<div id='navigation'>
<a href='users/home'>home</a> |
<a href='projects/browse'>home</a>
<a href='discussions/browse'>home</a>
<a href='search/dosearch'>home</a>
</div>
Run Code Online (Sandbox Code Playgroud)
注意我试过:
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
});
});
Run Code Online (Sandbox Code Playgroud)
但是,当我点击一个链接时,它会选择一个链接并添加类.selected但它重新加载页面以便导航到一个页面然后它全部消失.有小费吗?
谢谢
这应该工作:
$(document).ready(function() {
var loc = window.location.href; // The URL of the page we're looking at
$('#navigation a').each(function() {
if (loc.indexOf(this.href) !== -1) { // If the URL contains the href of the anchor
$(this).addClass('selected'); // Mark it as selected
}
});
});
Run Code Online (Sandbox Code Playgroud)
它基本上遍历导航项,如果当前页面的URL包含锚的href,它会将类添加selected到锚.
| 归档时间: |
|
| 查看次数: |
294 次 |
| 最近记录: |