我有一个带有左侧边栏 - 导航链接类的锚标记,在点击时应该检查href是否与网址匹配,如果匹配应该是粗体,但它只能点击两次,但不能一次。
<a class="left-sidebar-nav-link" href="#anchor"> SubMenu1</a>
$(document).ready(function() {
$(".left-sidebar-nav-link").on("click", function() {
var href1 = $(this).attr("href");
if (window.location.href.indexOf(href1) >= 0) {
$(this).css('font-weight', 'bold');
}
});
});
答案 0 :(得分:4)
$(document).ready(function() {
$(".left-sidebar-nav-link").on("click", function() {
window.location.href = $(this).attr("href");
var href1 = $(this).attr("href");
if (window.location.href.indexOf(href1) >= 0) {
$(this).css('font-weight', 'bold');
}
});
});
答案 1 :(得分:0)
由于href
使用event.preventDefault
$(document).ready(function() {
$(".left-sidebar-nav-link").on("click", function(event) {
event.preventDefault();
alert('1')
var href1 = $(this).attr("href");
if (window.location.href.indexOf(href1) >= 0) {
$(this).css('font-weight', 'bold');
}
});
});
答案 2 :(得分:0)
试试这个
$(document).ready(function() {
$(".left-sidebar-nav-link").on("click", function() {
var href1 = $(this).attr("href");
window.location.href = href1;
if (window.location.href.indexOf(href1) >= 0) {
$(this).css('font-weight', 'bold');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="left-sidebar-nav-link" href="#anchor"> SubMenu1</a>
答案 3 :(得分:0)
在逻辑方面,你的代码没有意义。您正在点击 标记,该标记会将网址更改为此标记的href
。因此,检查位置是否为href就像测试a标签是否有效一样。
发生双击是因为事件按此顺序发生:
event.preventDefault()
编辑:
更可靠的解决方案是拥有一个活动类,您将添加到您单击的项目中。
$('nav').delegate('.inactive', 'click', function(event) {
var selectedTab = this.id.split('-')[1];
document.location.hash = selectedTab;
var $this = $(this);
$this
.removeClass('inactive')
.addClass("active");
$this.siblings()
.addClass('inactive')
.removeClass('active');
});
body {
font: arial;
}
nav {
margin: 50px;
font-size: 2rem;
text-align: center;
}
ul {
display: inline-block;
list-style-type: none;
}
li {
height: 25px;
float: left;
margin-right: 0px;
padding: 0 20px;
}
li a {
text-decoration: none;
color: #878787;
text-transform: uppercase;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
-ms-transition: all 0.5s ease;
transition: all 0.5s ease;
}
li a:hover {
color: #666;
}
li.active a {
font-weight: bold;
color: #373737;
}
* {
box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<ul>
<li class="active" id="nav-tab1"><a>Tab1</a>
</li>
<li class="inactive" id="nav-tab2"><a>Tab2</a>
</li>
<li class="inactive" id="nav-tab3"><a>Tab3</a>
</li>
<li class="inactive" id="nav-tab4"><a>Tab4</a>
</li>
</ul>
</nav>
答案 4 :(得分:0)
终于!!,这对我有用,我试图触发哈希变化的点击事件
$(window).on('hashchange', function(e){
$(".left-sidebar-nav-link").on("click", function() {
window.location.href = $(this).attr("href");
var href1 = $(this).attr("href");
if (window.location.href.indexOf(href1) >= 0) {
$(this).css('font-weight', 'bold');
}
});
});