简体   繁体   English

将Click事件附加到div中的某些链接

[英]Attaching click event to certain links within a div

I have navigation divs with a number of links to both internal content and external pages. 我的导航div包含许多指向内部内容和外部页面的链接。 We are creating a vanilla javascript to intercept any clicks, determine the content required and insert it in the page, rather than reloading the entirety of the page everytime. 我们正在创建一个通用的javascript,以拦截所有点击,确定所需的内容并将其插入页面,而不是每次都重新加载整个页面。

Creating a script that uses a click event listener on the parent div worked superficially, fetching and inserting if you clicked on <a>, but also captured click events on any other text in the menu (titles and such) which subsequently failed: 创建在父div上使用click事件侦听器的脚本只是表面上的工作,如果您单击<a>会获取并插入,但是还捕获了菜单中其他任何文本(标题等)的click事件,这些事件随后失败了:

 $('#navfly').addEventListener('click', function(e) {
   var newpg = e.target.getAttribute('href');
   // take href value, modify url for content location
   // fetch content with ajax GET
   // insert within content div
   e.preventDefault();
 });

The nav div concept: 导航div概念:

 <div id="navfly">
 <a href="content-one.htm">Content 1</a><br>
 <a href="content-two.htm">Content 2</a><br>
 <a href="content-three.htm">Content 3</a><br>
 <a href="content-four.htm">Content 4</a><br>
 <a href="https://some.otherdomain.com">External wepage</a><br>
 </div>

I am looking for a way to target <a> within a specific div. 我正在寻找一种在特定div中定位<a>的方法。 In addition I need to be able to ignore clicks on some links and allow them to function as normals links. 另外,我需要能够忽略某些链接上的点击,并允许它们充当普通链接。

And contrary to my use of $( ) in the script, I am using vanilla javascript, NOT Jquery. 与我在脚本中使用$()相反,我使用的是普通javascript,而不是Jquery。 Just using a Jquery like querySelector function. 只需使用类似querySelector函数的Jquery。

Use Element.matches() to handle just the a tags you want: 使用Element.matches()仅处理所需的a标签:

 var navFly = document.querySelector('#navfly'); navFly.addEventListener('click', function(e) { // if it's not an a tag, that doesn't start with http do nothing if (!e.target.matches('a:not([href^="http"])')) { return; } e.preventDefault(); var newpg = e.target.getAttribute('href'); console.log(newpg); // take href value, modify url for content location // fetch content with ajax GET // insert within content div }); 
 <div id="navfly"> <a href="content-one.htm">Content 1</a><br> <a href="content-two.htm">Content 2</a><br> <a href="content-three.htm">Content 3</a><br> <a href="content-four.htm">Content 4</a><br> <a href="https://some.otherdomain.com">External wepage</a><br> </div> 

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

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