perform href before onClick

一笑奈何 提交于 2019-12-10 13:59:38

问题


I've the following link:

<a href="#HDR" onClick="showGallery()">I</a>

And this use the following javascript:

function showGallery(){
    if(window.location.hash) {
      $('#gallery').fadeIn('fast');
      var hash = window.location.hash.substring(1);
      alert(hash);
    } else {

    }

}

So it only show the gallery when in the URL is a hashtag. But when i click on the link, nothing happens. When i click it twice, the gallery fade in.

So the link first make the javascript, and i doesn't work 'cause there is no hashtag in the URL and after that, it perform the href and insert the Hashtag in the URL. How can i do that?

My Target:

When i click on a link, it open a gallery. To know which gallery i must open, i insert in the URL a Hashtag. Here i want to display the HDR album. And i also want, if my site get opend with a hashtag, it should display the gallery.!

Is there also a another, easier or cleaner way to make it? Hope you understand what i want.


回答1:


For modern browsers, you can bind your Javascript code to the onhashchange event. Links will be without Javascript:

<a href="#HDR">I</a>

And the Javascript is run whenever the hash has changed:

function locationHashChanged() {
    if (location.hash === "#HDR") {
        $('#gallery').fadeIn('fast');
    }
}

window.onhashchange = locationHashChanged;



回答2:


Have you tried a setTimeout call to delay the onclick event?

Like this:

<a href="#HDR" onClick="setTimeout(function(){showGallery.call(this)},20)">I</a>



回答3:


You can simplify this quite considerably, it is not good practice to use the href for other things than pure navigation.

<a onClick="showGallery('HDR')">I</a>

And then:

function showGallery(name){
    if(name) {
        $('#gallery').fadeIn('fast');
        alert(name);
    } else {

    }
}



回答4:


If you want to run showGallery() without following the link, the correct code is this:

<a href="#HDR" onClick="showGallery(); return false;">I</a>

By keeping the href the user still sees the destination in the status bar and navigation still works for clients without Javascript (i.e. Google). By returning false in the event handler, you prevent the browser from following the link.

In showGallery(), you can then show the gallery and add '#HDR' to the location.hash.




回答5:


You don't need to verify the window's hash, because on first click you don't have any hash in the address bar. The functionality will only apply on the second click.

What you can do is this:

<a href="#HDR" id="g1" onClick="showGallery('g1')">gallery 1</a>

function showGallery(galid){
    var linkhash = $('#' + galid).attr('href').substring(1);

    alert(linkhash);

    $('#gallery' + linkhash).fadeIn('fast');
}


来源:https://stackoverflow.com/questions/13743925/perform-href-before-onclick

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