當人們提到你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