尚未提及的另一个选项是将事件侦听器(例如使用jQuery)绑定到您关心的链接(可能全部是这些链接,可能不是)并让侦听器调用任何函数你用。评论后
编辑
例如,你可能有这样的代码在你的HTML:
然后,您可以添加以下代码绑定和回应链接:
$('a.myHash').click(function(e) {
e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
var linkHref = $(this).attr('href'); // Grab the URL from the link
if (linkHref.indexOf("#") != -1) { // Check that there's a # character
var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
alert(hash); // Just for fun.
}
});
请注意,我使用jQuery class selector来选择我想监视的链接,但是您可以使用wh atever selector你想要的。根据你现有的代码的工作方式,你可能需要修改你传递给它的方式/你可能需要建立一个完整的URL,包括新的散列,并传递它 - 例如,http://www.example.com/example#myanchor1),或者修改现有的代码以接受您通过新代码传递给您的代码。