简体   繁体   English

jQuery检测元素是否已链接到

[英]jQuery detect whether an element has been linked to

I want to attach a jQuery event handler to a <div> element such that whenever a link is clicked which points to this <div> , that handler is activated and the associated function is executed – regardless of the location of the link (same page, other page, other site) pointing to the <div> . 我想将jQuery事件处理程序附加到<div>元素,以便每当单击指向该<div>的链接时,都会激活该处理程序并执行关联的功能-不管链接的位置如何(同一页面) ,其他页面,其他站点)指向<div>

$("div#mydiv").on("linked_to", function(){ //is there a "linked_to" event?
  //do something about it
});

Is this possible? 这可能吗? Can scrollIntoView() be used? 可以使用scrollIntoView()吗?

What you want is quite specific and borderline undoable. 您想要的是非常具体的,并且无法取消。 I think your best bet is to detect a hash change in the URL and act accordingly. 我认为您最好的选择是检测URL中的哈希变化并采取相应的措施。

You aren't gonna be able to detect that div#mydiv itself was clicked, but detecting the hash #mydiv comes pretty close to it. 您将无法检测到div#mydiv本身已被单击,但是检测哈希值#mydiv非常接近它。

You would use something like: 您将使用类似:

  window.onhashchange = function() {
    if (window.location.hash === '#mydiv') { // here you check if it was `#mydiv`
      alert('hey! are you after mydiv?!')
    }
  }

Check an example here: http://output.jsbin.com/pikifov - click the link and notice how the hash from the URL changes. 在此处检查示例: http : //output.jsbin.com/pikifov-单击链接,并注意URL中的哈希如何变化。

Source for the JSBin above here . 上面JSBin的来源。

Full code: 完整代码:

 <div id="mydiv">mydiv</div> <hr> <a href="#mydiv">Click to go to mydiv</a> <script> window.onhashchange = function() { if (window.location.hash === '#mydiv') { alert('hey! are you after mydiv?!') } } </script> 

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

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