【发布时间】:2014-05-12 21:50:28
【问题描述】:
我为一个简单的下拉菜单编写了一些 javascript。但在我的下拉链接中,我使用主题标签作为 href 属性 (<a href="#") 的占位符,当点击它们时,页面会滚动回顶部。
我想用 jquery 的 .preventDefault(); 来防止这种情况发生,但我不确定我会在哪里以及如何用我的脚本来实现它。
示例:http://codepen.io/anon/pen/rwdoa(不幸的是,由于 iframe codepen 使用了 iframe,它不会将主题标签添加到 url)
// *************************************
//
// Navigation dropdown
// -> Expand/collapse submenus
//
// *************************************
// -------------------------------------
// Toggle .is-hidden class onclick and
// allow only one open menu at a time
// -------------------------------------
$(document).ready(function() {
$('.Navigation-listItem').click(function(e) {
if( $(this).children('.Navigation-list--dropdown').hasClass('is-hidden') ){
$(".Navigation-list--dropdown").addClass('is-hidden');
$(this).children('.Navigation-list--dropdown').removeClass('is-hidden');
} else {
$(".Navigation-list--dropdown").addClass('is-hidden');
}
});
$('.Navigation-listItem .Navigation-list--dropdown').click(function(e) {
e.stopPropagation();
});
});
// -------------------------------------
// Anything that gets to the document
// will hide the dropdown
// -------------------------------------
$(document).click(function(){
$(".Navigation-list--dropdown").addClass('is-hidden');
});
// -------------------------------------
// Clicks within the dropdown won't make
// it past the dropdown itself
// -------------------------------------
$(".Navigation-listItem--hasDropdown").click(function(e){
e.stopPropagation();
});
【问题讨论】:
-
我在想我应该添加函数 e.preventDefault();在第 15 行和第 42 行之前(行号在代码笔上)
标签: javascript jquery html drop-down-menu