定义事件委托者的正确语法

发布于 2024-07-26 22:01:47 字数 944 浏览 2 评论 0原文

通常,您会像这样编写按钮单击的处理程序:

$(document).ready(function()
{

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

但是在 事件委托者,使用如下函数响应事件:

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

我对此感到困惑定义调用此委托函数的事件的正确语法是 - this? (A):

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

还是这个? (B):

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

哪个是正确的,为什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

洒一地阳光 2024-08-02 22:01:47

在选择 A 中,您只需重复 document.ready 语法两次。

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

你需要做的就是选择B

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

时光磨忆 2024-08-02 22:01:47

如果您需要使用单独的函数,即您需要从单击按钮以外的其他地方调用该函数,那么选择 B 肯定是执行此操作的方法,但我的偏好通常是将代码放在一行中。 唯一我不这样做的时候是当它可以提高可读性时。

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

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');
        }
        ...
    });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文