Вы можете установить имя функции вашего метода для каждого элемента в атрибуте data-method
(чтобы избежать определения метода как пользовательского свойства самого HTML-элемента, что для некоторых считается плохой практикой из-за возможностипобочных эффектов).
Затем прослушайте событие hashchange
и загрузку страницы, чтобы найти элемент, соответствующий текущему значению хеш-функции, и вызвать его метод. Примечание: я использовал this
вместо window
для вызова функции метода, чтобы не зависеть от области действия.
// the method you want to be called when the page jumps to the element:
function contentElementMethod() {
console.log("the hash corresponds to the #content element!");
}
// the handler for getting the element corresponding to the current location hash and calling the method defined in its [data-method] attribute
function hashElementHandler() {
if (!window.location.hash) return; // we don't want to fire the first method found when there's no location hash set, e.g. when the page loads without one
var hashEl = document.querySelector(window.location.hash + '[data-method]');
if(hashEl) {
this[hashEl.getAttribute('data-method')]();
}
}
// listen to the hash change event
window.addEventListener("hashchange", hashElementHandler);
// also check the page hash on page load (wrap this
window.addEventListener('DOMContentLoaded', hashElementHandler);
<p><a href="#target">TARGET</a></p>
<div id="target" data-method="contentElementMethod">content</div>