定义事件委托者的正确语法
通常,您会像这样编写按钮单击的处理程序:
$(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在选择 A 中,您只需重复 document.ready 语法两次。
你需要做的就是选择B
In choice A you are just repeating the document.ready syntax twice.
All you need to do is choice B
如果您需要使用单独的函数,即您需要从单击按钮以外的其他地方调用该函数,那么选择 B 肯定是执行此操作的方法,但我的偏好通常是将代码放在一行中。 唯一我不这样做的时候是当它可以提高可读性时。
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.