繁体   English   中英

单击锚元素时:目标元素上是否触发了任何事件?

[英]When clicking on an anchor element: is there any event triggered on the target element?

我面临以下问题:

我有一个锚元素<a href="#target">TARGET</a>和一个目标元素<div id="target">content</div>

我想要做的是调用在目标元素上定义的方法。

此标准的原因是基于调用该方法的需要,即使链接来自另一个子页面。

我在研究之前的第一个想法是<div id="target" focus="myMethod">content</div>事件,但这并没有触发。

然后我开始研究W3schools HTML a 标签jQuery API以及Stackoverflow ofc。 但我没有找到任何相关的帖子(可能是由于关于“如何触发元素的点击事件”的大量问题)。

我很欣赏任何想法,花很多时间在上面:(

监听hashchange事件,然后在目标事件上触发自己的自定义事件。

$(document).on("hashchange", function() {
    $(window.location.hash).trigger("linkedto");
});

$("#target1").on("linkedto", function() {
    ...
});

您可以为data-method属性中的每个元素设置方法的 function 名称(以避免将该方法定义为 HTML 元素本身的自定义属性,由于可能存在副作用,这被某些人认为是不好的做法)。

然后监听hashchange事件以及页面加载,找到当前 hash 值对应的元素并调用其方法。 注意:我使用this而不是window来调用方法 function 以便与范围无关。

 // 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. eg 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM