2013-09-29 37 views
0

我正在嘗試使用this.evaluate()調用另一個模塊中定義的函數。

的代碼片段(調用函數)爲:

this.waitFor(function check() { 
    var re = this.evaluate(universe.answer(couponElement, url)); 
    if (re != 'no' & re!='yes' & re!=null) { 
     couponObj.push(re); 

並且其中該函數定義的模塊是這樣的:

var require = patchRequire(require); 

var utils = require('utils'); 
exports.answer = function(couponElement, url) { 
    var lblInvalidCoupon = 'lblInvalidCoupon'; 
    var tolTipCouponinner='tolTipCouponinner'; 
    var txtFCCoupondisocunt = 'txtFCCoupondisocunt'; 
    var btnRemoveFCCoupon = 'btnRemoveFCCoupon'; 

    var check = $('#txtCouponCode').css('backgroundImage'); 
    if (check.indexOf('ajax-loader.gif')>-1){   
     return 'no'; 
    } else { 
     if (document.getElementById(lblInvalidCoupon)!=null){ 

基本上,我想使用調用的函數this.evaluate但無法這樣做。

+0

您是否檢查過以確保遠程頁面已加載jQuery?您可以通過訪問瀏覽器中的頁面並嘗試使用瀏覽器的開發人員工具使用jQuery函數來完成此操作。 – hexid

+0

可能的重複[在JavaScript中,如果我用圓括號調用一個函數,它會有所作爲嗎?](http://stackoverflow.com/questions/3246928/in-javascript-does-it-make-a-difference-if -i-呼叫一個功能與 - 括號內) –

回答

0

首先,嘗試用最簡單的evaluateremote.message事件從頁面捕獲console.log

casper.on("remote.message", function(msg) { 
    console.log("[page] " + msg); 
}); 

this.evaluate(function() { 
    console.log("Hi phantomworld! I am hello-ing from remote page!"); 
}); 

接下來,檢查是否jQuery是存在:

this.evaluate(function() { 
    console.log(typeof jQuery); 
}); 

如果說,[page] function,jQuery的出現在頁面中。你需要挖掘更多...

如果不是,它注入:

var casper = require('casper').create({ 
    clientScripts: [ 
     'includes/jquery.js' 
    ] 
});  
-3

你實際上並沒有通過answer功能casper.evaluate,但你把它叫做替代。問題是以這種方式answer未在頁面上下文中執行,並且因此$未定義。在頁面上下文中執行函數的casper.evaluate被沙箱化。它不能使用外部定義的變量。傳遞的函數必須是自包含的。

要解決這個問題,answer消耗的參數可作爲附加參數傳遞給casper.evaluate

更改線路

var re = this.evaluate(universe.answer(couponElement, url)); 

var re = this.evaluate(universe.answer, couponElement, url); 

如果jQuery是不存在的,你需要遵循sudipto's answer頁面。