Jquery /javascript Based on hashtag in url find a tag that points to the same url and do something
I have a kind of complicated question here.
Right now I am running a script on my page that, when a user clicks on a link, I use jQuery's .load()
to load an image from a custom attribute called 'imglocation'.
This all works fine; my question is the link the 开发者_运维百科user clicks puts a hash tag in the url which i want to then use to match with a link on the page and run the same function as if the user clicked on it. The idea being that when you send someone a link when they open it in their browser the function will run and show the image that someone has sent to them.
What I was trying to do is:
var hashedLink = location.hash;
var findLink = $(".photothumb a").attr("href");
if(hashedLink == findLink){
// In here set some variable to flag the link
// then load the image based on the attr imgLocation of the same link.
}
If this is possible please let me know.
I think you want to do something like the following ...
$(document).ready(function()
{
var findLink = $(".photothumb a[href='" + location.hash + "']");
if (findLink.length > 0) // we found the link with the hash in the href
{
findLink.click(); // click the found link
}
}
I have not tested this, and you may want to play with the selector a tiny bit to make sure the hash tag exists in the href, but this should do what you want.
Most of what you are asking for should be trivial, except for the part where you 'emulate' a click on the link.
Links by default, do not have a click event; there are a myriad of ways to get a similar behavior, and you should use any of those variations, e.g. just call the function that the click event would have called, if a true click is not needed.
But if you really want to emulate a click on a link, you should read this post. Note that the only reason you would ever need to emulate a click is when you have a bunch of event handlers attached to that link, and you have no way of determining what those events are.
精彩评论