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

后端 未结 4 1202
既然无缘
既然无缘 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:36

    One benefit to having e (the object that raised the event) allows you to prevent the propagation of default behaviors for certain elements. For example:

    Click For Info
    

    renders a link that the user can click. If a user has JavaScript disabled (why? I dunno), you want the user to navigate to someOtherPage.htm when they click the link. But if they have JavaScript enabled, then you want to display a modal dialog and not navigate away from the page. You would handle this by preventing the default behavior of the anchor/link and displaying the modal as such:

    $("#navLink").click(function(e) {
      e.preventDefault();  //this prevents the user from navigating to the someOtherPage.htm
      $("#hiddenDiv").dialog({
        //options
      });  //show the dialog
    });
    

    So having that parameter available allows you to, among other things described in other answers, prevent the default behavior of the selected element.

    Hope this helps!

提交回复
热议问题