jquery/[removed] function(e){… what is e? why is it needed? what does it actually do/accomplish?

后端 未结 4 1201
既然无缘
既然无缘 2020-11-30 23:48
$(\'#myTable\').click(function(e) {
    var clicked = $(e.target);
    clicked.css(\'background\', \'red\');
});

Can someone explain this to me, an

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 00:19

    I'm speaking in theory as to I'm no expert but I achieved the desired result by using he the little (e) which doesn't have to be an e lol

    I figured it out. It's a way of passing the same event from one function to another.

    In simpler terms. I wanted to make the page navigation an elastic scroll function, however, I wanted the page to navigate by hover "and" I wanted the same navigation to be clickable upon certain conditions. I also wanted the same dynamic navigation from other click events that were not links. To keep the current target and still use the navigation function I had to set the little (e) because jQuery will lose the scope of $(this) as the same target of the function lol. Here's a quick example.

    function navigate_to_page(e){
    var target = $(e.currentTarget).attr('href'); //--This is the same as $(this) but more static to bring out of it's scope
        $('html, body').animate({
        'scrollTop':$(target).offset().top-0,
        'scrollLeft': $(target).offset().left-$(window).width()*0.0}, 2000, 'easeOutBounce');
    }
    

    Don't let the gibberish confuse you. It's just a simple page scroll animation. The thing to pay attention to is the e.currentTarget. e is our variable and currentTarget is a jQuery equivalent to $(this) so those together is a Globular $(this) function. Now I call it by another function with condistions like so

    $('#myNavigationDiv a').on('mouseenter', function(e){
        if($(myCondition) === true){
            return false;
            }else{
            navigate_to_page(e);
            }
        });
    

    See how the little (e) linked everything together?

    Now you can substitute (e) to (whateveryouwant). By calling e in both functions it matched e.currentTarget and you can apply this to whatever detailed specific functions you need and save yourself LITERALLY pages of code lol

提交回复
热议问题