所以我制作了这段代码,它几乎可以完美运行。一件事是 setupListener 方法最后返回错误,可能它找到了我不想找到的属性。我已经为此苦苦挣扎了一段时间,但显然我没有太多的 js 经验来解决它。我已经设置了一些用于调试的 console.log 方法。你像这样使用这个函数setupListener(Id or Class or a Tag name as string, event to watch on as string, and an action)
:
例如。setupListener('.pun', 'click', function (e){ console.log(e); });
var getElement = function (onStr) {
if (onStr.indexOf('.') === 0) {
onStr = onStr.slice(1);
return document.getElementsByClassName(onStr);
}
if (onStr.indexOf('#') === 0) {
onStr = onStr.slice(1);
return document.getElementById(onStr);
}
if (onStr.indexOf('#') !== 0 && onStr.indexOf('.') !== 0) {
return document.onStr = document.getElementsByTagName(onStr);
}
};
var setupListener = function (elementStr, eventStr, action) {
var tempElement = getElement(elementStr);
// element a collection and has addEventListener method
if (tempElement.length > 1 && tempElement[1].addEventListener) {
for (var i = 1; tempElement.length >= i; i++) {
if (typeof(tempElement[i].addEventListener) !== "undefined")
console.log('1'); //debugging
tempElement[i].addEventListener(eventStr, action);
}
}
// IE < 9 Support
// element a collection and has NOT addEventListener method
else if (tempElement.length > 1 && !tempElement[1].addEventListener) {
for (var i = 1; tempElement.length >= i; i++) {
if (typeof(tempElement[i].addEventListener) !== "undefined")
console.log('2'); // debugging
tempElement[i].attachEvent(eventStr, action);
}
}
// element not a collection and HAS addEventListener method
else if (!tempElement.length > 1 && tempElement.addEventListener) {
console.log('3'); // debugging
tempElement.addEventListener(eventStr, action);
}
// element not a collection and has NOT addEventListener method
// IE < 9 support
else if (!tempElement.length > 1 && !tempElement.addEventListener) {
console.log('4'); // debugging
tempElement.attachEvent(eventStr, action);
}
else {
console.log('5'); // debugging
}
};