我有以下jQuery / JS,当单击某个元素时会触发一些操作:
$(tabs).click(function(e) {
tabs.removeClass('active');
$(this).addClass('active');
$(tabIDs).removeClass('js_tab_area_show');
$($(this).attr('href')).addClass('js_tab_area_show');
e.preventDefault();
alert('worked');
});
tabs
在此函数之前已初始化,并选择了我要定位的元素。以上所有内容均已正常运行。但是,我现在想禁止锚元素(在这种情况下为tabs
)滚动到具有我的锚的href
属性中包含的ID的元素。我尝试环顾四周,并建议使用preventDefault()
来防止滚动。但是,它对我不起作用。我最常看到的唯一区别是,它们具有一个专门用于处理单击事件的命名函数,该命名事件是在click函数中调用的。另一方面,我的做到了。 alert('worked')
确实触发,指示执行到最后的代码。我在这里做错了什么?
答案 0 :(得分:0)
href
修改执行以下操作,而不是过度复杂化JavaScript / jQuery或CSS。
<a href="#/">I DON't JUMP</a>
只需添加正斜杠:/
如果您有大量链接,但没有可用的服务器端实用程序,请参见演示2 。它有一个简单的JavaScript链接收集器。
h1,
h2 {
text-align: center
}
h2 {
font-size: 64px
}
a {
display: inline-block;
height: 30px;
font-size: 24px;
width: 40%;
margin: 400px 0;
}
a:first-of-type {
color: red;
text-align: right;
}
a:last-of-type {
color: blue;
text-align: left;
}
<main>
<h1>Scroll Down</h1>
<h2>⇩</h2>
<a href="#">Click me.<br>I JUMP.</a>
<a href="#/">Click me.<br>I DO NOT JUMP.</a>
</main>
Array.from(document.querySelectorAll('a')).forEach(lnx => {
if (lnx.getAttribute('href') === '#') lnx.setAttribute('href', "#/");
});
h1,
h2 {
text-align: center
}
h2 {
font-size: 64px
}
main {
margin: 400px auto;
}
a:nth-of-type(odd) {
background: #000;
color: #fff;
}
a:nth-of-type(even) {
color: #000;
}
<h1>Scroll Down</h1>
<h2>⇩</h2>
<main>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
<a href='#'>WE DON'T JUMP</a>
</main>