你需要覆盖querySelector
和querySelectorAll
在HTMLElement
和HTMLDocument
对象的prototype
。但是您肯定需要存储/保留原始功能,以便您不会破坏代码。
你可以做这样的事情:
(function() {
function wrapQueryFunction(name) {
[HTMLElement, HTMLDocument].forEach(function(obj) {
//store the original function
var origQueryFunction = obj.prototype[name];
//replace the function with the own wrapper
obj.prototype[name] = function(selector) {
logSelector(this, selector);
//call the original function and return the result
return origQueryFunction.apply(this, arguments);
}
});
function logSelector(elm, selector) {
console.log('selector: ' + selector);
}
}
wrapQueryFunction('querySelector');
wrapQueryFunction('querySelectorAll');
}());
非常感谢你,这就像一个魅力! –