寻找有关正确使用 preventDefault() 的一些建议 - 代码如下。简而言之,我不希望 a.dropdownTrigger 点击事件跳转到锚点。我认为插入 event.preventDefault() 作为该函数的第一行就可以了,但显然不是。
认为它可能与绑定 hashchange 事件有关,我用它来监视对 url 的更改(单击 a.dropdownTrigger 元素会更新哈希位置,它会在 hashchange 上调用侦听器 - 这样做可以让我捕获到下拉触发器的入站链接,并维护 url 历史记录)。
有什么想法我哪里出错了吗?
// check inbound anchor links against dropdown ids
if (hash != "" && dropdowns.length != 0 && $.inArray(hash, dropdowns)) {
OpenDropdownForHash(hash);
}
// listen for hashchange once page loads (handles on-page links to dropdown content)
$(window).bind('hashchange', function () {
hash = window.location.hash;
if (dropdowns.length != 0 && $.inArray(hash, dropdowns)) {
OpenDropdownForHash(hash);
}
});
// open the targeted dropdown - var incoming is a bool, differentiate between inbound links and on-page clicks
function OpenDropdownForHash(x) {
$(x).next('.dropdown').toggleClass('open').slideToggle(200);
if ($(x).next('.dropdown').hasClass('open')) { //can this live in the callback above?
$(x).parent().css("-webkit-transition", "all 0.8s ease")
.css("backgroundColor", "white")
.css("-moz-transition", "all 0.8s ease")
.css("-o-transition", "all 0.8s ease")
.css("-ms-transition", "all 0.8s ease")
.css("backgroundColor", '#eeeeee').delay(600).queue(function () {
$(this).css("backgroundColor", "white");
$(this).dequeue(); //Prevents holding color with no fadeOut on second click.
});
}
}
// finally, the basic click handler for dropdowns - update the hash (to allow history), which triggers previously bound hashchange event
$('a.dropdownTrigger').bind('click',function (e) {
e.preventDefault();
if ("#" + $(this).attr('id') == location.hash) { // clicking an open dropdown link doesn't trigger the hashchange event, so we check manually
OpenDropdownForHash("#" + $(this).attr('id'));
}
else { // clicking a closed dropdown does call hashchange, so the OpenDropdownForHash function is called by the listener
location.hash = $(this).attr('id');
}
});
更新:用更多的努力解决了这个问题,重新设计了点击处理程序并简化了 hashchange 监听器:
if (dropdowns.length != 0) {
// the basic click handler for dropdowns - update the hash (to allow history), which triggers previously bound hashchange event
$('#mainContentContainer a').bind('click', function (e) {
var target = $(this).attr('href') != null ? $(this).attr('href') : "#" + $(this).attr('id');
var offset = window.pageYOffset;
if ($.inArray(target, dropdowns) && location.hash != target) {
location.hash = target;
window.scrollTo(0, offset);
}
else if ($.inArray(target, dropdowns) && location.hash == target) {
OpenDropdownForHash(location.hash, $(this).hasClass('dropdownTrigger'));
window.scrollTo(0, offset);
}
});
}
$(window).bind('hashchange', function(e) {
OpenDropdownForHash(location.hash, $(this).hasClass('dropdownTrigger'));
});