使用 jQuery 将函数惰性绑定到多个事件
场景如下:我有一组按钮,我想在单击它们时将其绑定到相应的功能。 这些按钮的 id 与其对应功能的名称相同。 我可以这样做:
$("#kick").click(kick);
$("#push").click(push);
$("#shove").click(shove);
但我很懒,并且想更懒地这样做(这是我的本性)。 由于按钮全部包含在块元素中,我想做这样的事情:
$("#button_holder > span").each(function () {
var doThis = this.id;
$(this).click(doThis);
});
但那不起作用。 有什么建议么?
Here's the scenario: I have a set of buttons that I want to bind to corresponding functions when clicked. The ids of these buttons are the same as the names of their corresponding functions. I could do this:
$("#kick").click(kick);
$("#push").click(push);
$("#shove").click(shove);
But I'm lazy and would like to do this more lazily (as is my nature). As the buttons are all contained in a block element, I'd like to do something like this:
$("#button_holder > span").each(function () {
var doThis = this.id;
$(this).click(doThis);
});
Except that doesn't work. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
和其他回答者一样,我不确定这是“真正的”懒惰(如程序员的美德),但只有你知道你的实现细节。
如果你确实想做这样的事情,你可以使用一个对象来存储你的特定函数,然后使用字符串来查找它们:
或者作为匿名函数:
Like the other answerers, I'm not sure that this is "true" laziness (as in the programmer's virtue), but only you know your implementation details.
If you really want to do something like this, you can use an object to store your particular functions and then use the string to look them up:
Or as anonymous functions:
我想我不明白这有什么意义。 无论如何,您都需要单独创建每个函数,而这种编程对其他人来说通常很难理解。 也许如果你有几十个按钮并且它是一次性代码,我可以理解,但是..可能不能...
为什么不将所有按钮都绑定到一个函数并在事件时根据 this.id 做出决定?
I guess I don't see the point of this. You need to create each function individually anyway and this sort of programming is difficult for others to grok usually. Maybe if you have dozens of buttons and it's throw-away code, I could understand but .. probably not...
Why not just bind all to a single function and make the determination based on this.id at event time??
很简单!
您尝试将无功能传递给 click 方法。
你需要传递一个函数:
});
或者 :
its very simple !
you try to pass none-function to the click method.
you need to pass a function :
});
or :