jQuery code affecting my HTML image links?

不羁的心 提交于 2019-12-10 13:37:25

问题


$(document).ready(function(){
  $('body a').click(function(e){
    e.preventDefault();
    var goTo = $(this).attr('href').replace('#','');
    $('html, body').animate({
        scrollTop:$('a[name="'+goTo+'"]').offset().top
    },1775);

    window.location.hash = "#"+goTo;

});

I have this function in my code to achieve a scrolling effect on my page, however I think it is affecting my image links. When I click on an image it doesn't link anywhere. I'm fairly certain the error is somewhere here but need some help finding it.

Thanks.


回答1:


Make sure there is a hash # in the href first before changing anything so normal links will still work.

One way is check hash property of the element

if(this.hash){
  e.preventDefault();
  // rest of code shown 
}

Can also use attribute selector to filter out only links with # in href

 $('body a[href^=#]').click...

Last one assumes all hash links are relative and href starts with #



来源:https://stackoverflow.com/questions/37635989/jquery-code-affecting-my-html-image-links

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!