显然,您可以遍历元素并在循环内分配处理程序:
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() ...