简体   繁体   English

链接点击事件被父mousedown事件阻止

[英]Link click event blocked by parent mousedown event

I have a link inside a header such as this 我在这样的标题中有一个链接

<table id="mytable" border=1>
<thead>
  <th id='myHeader'><a href="#" class="sortHeader">HelloWorld</a></th>
</thead>
</table>

And some sample javascript, hooking up a click event on the link, and a mousemove event on the table header element. 还有一些示例javascript,在链接上关联了click事件,在表头元素上关联了mousemove事件。

var randomFunction = function(event, id){
    alert('header was moved');
}

$('#mytable').on('click', '.sortHeader', function(evt){
    alert('header was clicked')
});

var header = document.getElementById('myHeader');
header.addEventListener('mousedown', randomFunction);

Unfortunately, when I add the mousedown, the click event no longer is set off by a click. 不幸的是,当我添加mousedown时,单击事件不再被单击触发。 I've checked the events in google developer tools, and they're both there. 我已经在Google开发人员工具中检查了事件,它们都在那儿。 How do I get the click event to fire? 如何触发点击事件?

Here's a full jsfiddle: https://jsfiddle.net/nickwinters/xLz8agy0/1/ 这是完整的jsfiddle: https ://jsfiddle.net/nickwinters/xLz8agy0/1/

You need to use console.log(); 您需要使用console.log(); instead of alert() . 而不是alert()

Because on mouse down your calling the alert() function which interrupts with mouseup in click function, hence alert in the click function is not triggered. 因为在鼠标按下时您调用的alert()函数会在click函数中被mouseup中断,因此不会触发click函数中的alert

Here is an example of having two click events, one inside the other. 这是一个具有两个单击事件的示例,一个在另一个内部。 By using the stop propagation function on the click event you can stop the event from bubbling up and triggering the other event. 通过在click事件上使用停止传播功能,可以阻止事件冒泡并触发另一个事件。

'use strict';

let outer = document.querySelector('.outer');
let inner = document.querySelector('.inner');

let outerClick = (e) => {
  alert('outer clicked');
}

let innerClick = (e) => {
  e.stopPropagation();
  alert('inner clicked');
}

outer.addEventListener('click', outerClick);
inner.addEventListener('click', innerClick);

https://jsfiddle.net/pz47f1kx/ https://jsfiddle.net/pz47f1kx/

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

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