当人们提到你bind
在JavaScript中在这种情况下,它们很可能是指jQuery的.bind()
函数,而不是ECMAScript 5的Function.bind
(ECMAScript 是 JavaScript ......基本上)。
正如@morgancodes在评论中暗示的那样,你实际寻找的概念是事件委托。如果您想要了解如何在JavaScript中执行此操作,您需要查看PPK's DOM Events并了解如何在IE中规范化事件对象。这是很多工作,但最终值得。
在另一方面,如果你想现在更新的代码,你可以使用许多JavaScript库在那里的一个应对正火为您提供:
在jQuery中,例如,你可以绑定你点击事件,你的链接在以下任何一种方式:
// Bind the event directly to the element.
// Advantages: clear, quick (to code)
// Disadvantages: not good for dynamically added links
// or in cases where you have a lot of links.
$("your_link_selector").click(function() { /* do your stuff here */ });
// Alternate:
$("your_link_selector").bind("click",function() { /* do your stuff here */ });
// Bind the event to the body and fire it when the selector matches.
// Advantages: works with dynamic content, lots of links.
// Disadvantages: slower than delegate when you have lots of live events.
$("your_link_selector").live("click",function() { /* do your stuff here */ });
// Bind the event to the selected container elements
// Fire the event when the event_selector matches.
// Advantages: works with dynamic content, lots of links.
// Disadvantages: There are disadvantages? ;-)
$("your_container_selector").delegate("your_link_selector",
"click",
function() { /* do your stuff here */ });
任何其他JavaScript库将有能力处理这个问题,以及 - 我避免为了保持较短的后加入的例子。
你的意思是* onclick事件将在页面加载时加载*? “加载事件”意味着什么? – Cheeso 2011-05-04 16:19:59
@Cheeso:我可能是错的,但我认为随着页面加载它将事件存储在内存中准备激活,而不是在链接被点击时运行查询。这可以加快这一进程。 – Hatzi 2011-05-04 16:28:27
我很久以前就停止在我的html标签中写javascript了。用户界面的复杂性不仅仅是微不足道的,当您在脚本中注册事件而不是内联时,它更加清洁和更好。当你了解这一点时需要注意的事情是事件代表团,它允许你在创建dom元素之前注册事件。如果您要动态添加和删除大量链接,事件委派可以帮助您编写更简单的代码。 – morgancodes 2011-05-04 16:39:07