How to create click event handler inside mouseover

2019-07-05 14:16发布

问题:

I'm trying to build some kind of element inspector (like in Chrome/FF).

Flow is as follows:

  1. You click 'Start inspecting' button.
  2. You hover over necessary element.
  3. You click on that element.
  4. You should see that element in console.

JSFiddle example

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.logs 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!

回答1:

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);
    });
};

DEMO



回答2:

I'd suggest breaking it up into parts. The user clicks on "Start Inspecting" and your page goes into inspecting mode where it adds css dynamically to every element that is hovered over so it looks similar to Chrome. When you click on an element in inspecting mode then you can handle it how you want. This way you only have to add one hover and one click handler per element, thus only triggering the event once.