Correct syntax for defining an event delegator

爱⌒轻易说出口 提交于 2019-12-12 03:53:24

问题


Normally you write a handler for a button click like this:

$(document).ready(function()
{

  $("button").click(function()
  {    
    doSomething();
  });
});

But in the case of an event delegator, to respond to an event with a function such as this:

  function doSomething(event)
  {
    if (ev.target.id == 'button1' )
    {
       //do your stuff
       console.log('#button1 click');
    }
    else
    {
       console.log('not a #button1 click');
    }
  }

What I'm confused about is the correct syntax for defining the event that calls this delegator function - this? (A):

$(document).ready(function()
{
  $(function()
  {
    $('button').click(doSomething);
  });
});

or this? (B):

$(document).ready(function()
{
  $("button").click(doSomething);
});

Which is correct and why?


回答1:


In choice A you are just repeating the document.ready syntax twice.

// These two lines are equal
$(document).ready(fn);
$(fn);

All you need to do is choice B




回答2:


While choice B would certainly be the way to do this if you needed to use a separate function, i.e., in the case where you needed to invoke the function from somewhere other than a button click, my preference is usually to put the code in line. The only other times I don't do this is when it would improve readability.

$(function() {
    $("button").click( function(e) {
        if (e.target.id == 'button1') {
           alert('button1 clicked');
        }
        ...
    });
});


来源:https://stackoverflow.com/questions/1147864/correct-syntax-for-defining-an-event-delegator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!