顯然你可以遍歷所有的元素和分配處理程序的循環中:
function onChangeHandler() {
// do some stuff
}
var myCollection = document.getElementsByName("attribute.Identifier Source");
for (var i=0, l=myCollection.length; i<l; i++)
myCollection[i] = onChangeHandler;
或者,如果你想有改變的元素的引用:
function onChangeHandler(event) {
// some browser abstraction
if (!event) event = window.event;
var changedElement = event.srcElement || this;
// do some stuff
}
var myCollection = document.getElementsByName("attribute.Identifier Source");
for (var i=0, l=myCollection.length; i<l; i++) {
myCollection[i].addEventListener('change', onChangeHandler, false);
/* if you want to support older MSIE, you would do some like
var el = myCollection[i];
if (el.addEventListener) {
el.addEventListener('change', onChangeHandler, false);
}
else if (el.attachEvent) {
el.attachEvent('onchange', onChangeHandler);
}
*/
}
請注意,document.getElementsByName()僅支持XHTML,您可能想要使用document.querySelectorAll()或document.getElementsByTagName()...