定义事件委托人的正确语法 [英] Correct syntax for defining an event delegator
本文介绍了定义事件委托人的正确语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常,您为按钮单击编写处理程序,如下所示:
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');
}
}
我感到困惑的是定义调用此委托函数的事件的正确语法-这是吗? (A):
$(document).ready(function()
{
$(function()
{
$('button').click(doSomething);
});
});
还是这个? (B):
$(document).ready(function()
{
$("button").click(doSomething);
});
哪个是正确的,为什么?
推荐答案
在选项A中,您只是重复了document.ready语法两次.
In choice A you are just repeating the document.ready syntax twice.
// These two lines are equal
$(document).ready(fn);
$(fn);
您需要做的就是选择B
All you need to do is choice B
这篇关于定义事件委托人的正确语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文