jQuery preventDefault不阻止锚的行为 [英] jQuery preventDefault not prevent anchor's behaviour
问题描述
我有一个菜单,可以过滤类别并隐藏或显示单击的类别.筛选工作正常,但由于某些原因,我无法停止锚的默认行为.锚点带有一个#",每次单击它都会带您到页面顶部,这不是一个好的UX.我需要它保持原样,以便进行过滤而不会将用户移动到页面顶部.任何帮助,将不胜感激.谢谢,
I have a menu that filters through categories and hides or displays whatever category is clicked on. The filtering is working fine but for some reason I can't stop the anchor's default behaviour. The anchor has a '#' and every time it is clicked it takes you to the top of the page which is no good UX. I need it to stay where it is so that filtering happens without moving the user to the top of the page. Any help would be appreciated. Thanks,
这是我的jquery:
Here is my jquery:
$(".portfolio-nav li:first-child").addClass("active");
//Filter through Categories
$(".portfolio-nav ul li a").click(function(e){
e.preventDefault();
//Add class active to the nav item
$(".portfolio-nav li").removeClass("active");
$(this).parent().addClass("active");
//Get the filter data
var filter = $(this).data('filter');
//set 'All' filter value
if(filter == '*'){
filter = 'category';
}
//Hide all categories
$(".categories").children("div").not('.'+filter).css({'width':'0', 'height':'0', 'opacity':'0', 'padding':'0', 'margin':'0'});
//Fade In filters after categories fade out
$(".categories").children('.'+filter).css({'width':'48%', 'height':'300px', 'opacity':'1', 'padding':'0', 'margin':'1%'});
});
这是我的标记:
<div class="portfolio-nav block row">
<ul class="inline center block">
<li class="pills slow">
<a href="#" data-filter="*">
All
</a>
</li>
<li class="pills slow">
<a href="#" data-filter="websites">
Websites
</a>
</li>
<li class="pills slow">
<a href="#" data-filter="ecommerce">
E-Commerce
</a>
</li>
<li class="pills slow">
<a href="#" data-filter="apps">
Apps
</a>
</li>
<li class="pills slow">
<a href="#" data-filter="tools">
Tools
</a>
</li>
</ul>
</div>
推荐答案
看来main.js第93行上的这段代码正在使定位标记跳到页面顶部:
It appears that this piece of code on line 93 of main.js was causing the anchor tag to jump to the top of the page:
var a=document.getElementsByTagName("a");
for(var i=0;i<a.length;i++) {
if(!a[i].onclick && a[i].getAttribute("target") != "_blank") {
a[i].onclick=function() {
window.location=this.getAttribute("href");
return false;
}
}
}
更改点击处理程序,以不将window.location
设置为基本上空白的href
:
Change the click handler to not set the window.location
for an essentially blank href
:
a[i].onclick=function() {
if(this.getAttribute("href") !== '#') {
window.location=this.getAttribute("href");
return false;
}
}
您会很好!
这篇关于jQuery preventDefault不阻止锚的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!