如何在mouseover事件处理程序中创建点击事件处理程序? [英] How to create click event handler inside mouseover event handler?
问题描述
流程如下:
- 您点击'开始检查'按钮。
- 将鼠标悬停在必要的元素上。您可以点击该元素。
- 您应该在控制台中看到该元素。
以下是代码:
$('section *')。on('mouseover。')。 startInspecting = function(){
$ INSPECTOR',函数(e){
$('。hovered-element')。removeClass('hovered-element');
$(e.target).addClass('hovered-element') ;
$(this).on('click.INSPECTOR',function(e){
$('section *')。off('mouseover.INSPECTOR');
$( 'section *')。off('click.INSPECTOR');
$('。hovered-element' ).removeClass(hovered-element);
console.log(e.target);
});
});
};
问题在于:每次我将鼠标悬停在某个元素上时 - 单击事件处理程序附加到它。所以如果我将鼠标悬停在 p
元素上5次,然后点击它 - 我会看到5 console.log
s而不是1 。
我试图用 mouseenter / mouseleave
来实现它,但面临的问题,每个元素只能被徘徊一次 -
所以无论我将鼠标悬停在元素上多少次,它只会有一个点击处理程序,我该如何改进我的代码?
在此先感谢您,任何帮助我们都将不胜感激!
c> onclick mouseover
?
<$ c $ (''mouseover.INSPECTOR',function(e){
$('。hovered-element')。removeClass(' hovered-element');
$(e.target).addClass('hovered-element' );
))。on('click.INSPECTOR',function(e){
$('section *')。off('mouseover.INSPECTOR click.INSPECTOR');
console.log(e.target);
});
};
I'm trying to build some kind of element inspector (like in Chrome/FF).
Flow is as follows:
- You click 'Start inspecting' button.
- You hover over necessary element.
- You click on that element.
- You should see that element in console.
Here is the code:
startInspecting = function(){
$('section *').on('mouseover.INSPECTOR', function(e){
$('.hovered-element').removeClass('hovered-element');
$(e.target).addClass('hovered-element');
$(this).on('click.INSPECTOR', function(e){
$('section *').off('mouseover.INSPECTOR');
$('section *').off('click.INSPECTOR');
$('.hovered-element').removeClass("hovered-element");
console.log(e.target);
});
});
};
The problem is: each time I hover over some element - click event handler is attached to it. So if I hover over p
element 5 times, and then click on it - I will see 5 console.log
s instead of 1.
I tried to implement it using mouseenter/mouseleave
, but faced the issue, that each element can be hovered only once - another JSFiddle example
So how can I improve my code that no matter how many times I hover over the element, it will have only one click handler?
Thanks in advance, any help will be appreciated!
Did you try moving the onclick
handler outside the mouseover
?
startInspecting = function(){
$('section *').on('mouseover.INSPECTOR', function(e){
$('.hovered-element').removeClass('hovered-element');
$(e.target).addClass('hovered-element');
}).on('click.INSPECTOR', function (e) {
$('section *').off('mouseover.INSPECTOR click.INSPECTOR');
console.log(e.target);
});
};
这篇关于如何在mouseover事件处理程序中创建点击事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!