[Javascript][jQuery] 動態建立元素的事件觸發
類型:
Javascript
我們有個舊專案使用早期的jQuery 1.2,剛巧新增功能的動態建立新元素讓原有的事件無法被觸發,測試後才知道「的有元素」的事件程式無法套用給「未來動態建立的元素」,在jQuery 1.7後使用 .on() 就能有效處理的有與未來元素的事件作業了。
▼ 測試網頁
![Flash2u 在新視窗檢視]()
靜態 tr 元素一切正常
表格 TABLE1 原本有5個靜態的 tr,點選換背景色與刪除、修改等皆能正常運作。但按下〔Add〕動態新增的 tr 完全無法觸發這些 click 事件。
.highlight {
color: white;
background-color: highlight;
}
[i]
static text 1[i][i]
static text 2[i][i]
static text 3[i][i]
static text 4[i][i]
static text 5[i][i]
動態建立的新元素
只要把 click 事件改寫成 .delegate() 或 .on() 才能解決這個問題。範例直接使用 .on()和.delegate() 來撰寫。.on()的使用語法是:
selector.on( events [, sub-selector ] [, data ], handler )
例如:
$("table tr").on("click", "td:nth-child(1)", function() {
// some code...
});
修改後的原始碼如下:
.highlight {
color: white;
background-color: highlight;
}
[i]
static text 1[i][i]
static text 2[i][i]
static text 3[i][i]
static text 4[i][i]
static text 5[i][i]
測試基本資料下載或執行
點選執行或按右鍵另存新檔。
靜態元素版本:http://jdev.tw/files/table1-step1.html
動態元素版本:http://jdev.tw/files/table1-step2.html
##
-->
想在手機查閱更多Javascript資訊?免費下載【香港矽谷】Android App
![Flash2u 在新視窗檢視]()
原文站台: 簡睿 JDev.tw
![Flash2u 在新視窗檢視]()
分享到Facebook
類型:
Javascript
我們有個舊專案使用早期的jQuery 1.2,剛巧新增功能的動態建立新元素讓原有的事件無法被觸發,測試後才知道「的有元素」的事件程式無法套用給「未來動態建立的元素」,在jQuery 1.7後使用 .on() 就能有效處理的有與未來元素的事件作業了。
▼ 測試網頁

靜態 tr 元素一切正常
表格 TABLE1 原本有5個靜態的 tr,點選換背景色與刪除、修改等皆能正常運作。但按下〔Add〕動態新增的 tr 完全無法觸發這些 click 事件。
.highlight {
color: white;
background-color: highlight;
}
[i]
static text 1[i][i]
static text 2[i][i]
static text 3[i][i]
static text 4[i][i]
static text 5[i][i]
動態建立的新元素
只要把 click 事件改寫成 .delegate() 或 .on() 才能解決這個問題。範例直接使用 .on()和.delegate() 來撰寫。.on()的使用語法是:
selector.on( events [, sub-selector ] [, data ], handler )
例如:
$("table tr").on("click", "td:nth-child(1)", function() {
// some code...
});
修改後的原始碼如下:
.highlight {
color: white;
background-color: highlight;
}
[i]
static text 1[i][i]
static text 2[i][i]
static text 3[i][i]
static text 4[i][i]
static text 5[i][i]
測試基本資料下載或執行
點選執行或按右鍵另存新檔。
靜態元素版本:http://jdev.tw/files/table1-step1.html
動態元素版本:http://jdev.tw/files/table1-step2.html
##
-->
想在手機查閱更多Javascript資訊?免費下載【香港矽谷】Android App

原文站台: 簡睿 JDev.tw

分享到Facebook