gpt4 book ai didi

javascript - 如何在我的下拉脚本中使用 preventDefault?

转载 作者:行者123 更新时间:2023-11-28 04:34:21 30 4
gpt4 key购买 nike

我已经为一个简单的下拉菜单编写了一些 javascript。但是在我的下 zipper 接中,我使用井号标签作为 href 属性 ( <a href="#") 的占位符,当它们被点击时,页面会滚动回顶部。

我想用 jquery 的 .preventDefault(); 来防止这种情况发生但我不确定在何处以及如何使用我的脚本实现它。

示例:http://codepen.io/anon/pen/rwdoa (它不会将主题标签添加到 url,因为不幸的是使用了 iframe codepen)

// *************************************
//
// 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();
});

最佳答案

视情况而定,但有一种方法是这样的

$('.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');
}
}).children('a.Navigation-link--dropdownTrigger').click(function(e){e.preventDefault();}); // add this line

demo

关于javascript - 如何在我的下拉脚本中使用 preventDefault?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23536350/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com