2016-05-10 115 views
2

我正在使用PhantomJS來獲取和評估網站。在評估中,我大量使用querySelector(selector)querySelectorAll(selector)。由於網站的HTML有時會發生變化,我不得不一次更改選擇器或添加新的選擇器。現在我不確定哪些選擇器仍在使用中,哪些是不再運行並可以刪除的代碼。如何裝飾JS中的querySelector/querySelectorAll

我想裝飾這些方法並記錄在裝飾函數中使用過的選擇器。我想這比在主代碼中添加所有日誌處理好得多。任何想法如何實現這一目標?

回答

1

你需要覆蓋querySelectorquerySelectorAllHTMLElementHTMLDocument對象的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'); 
}()); 
+0

非常感謝你,這就像一個魅力! –