Clicking an element using casperjs's evaluate

2019-09-17 09:21发布

问题:

I am trying to use jQuery and casperjs to click an element retrieved from the DOM.

casper.options.clientScripts = ["jquery-1.11.1.min.js"];
...
...
casper.then(function()
{   
    this.wait(2000,function()
    {
        this.evaluate(function()
        {

        var element = $('h4:contains("test")').prev().find('.delete');
        $(element).css("background-color", "red");

        $(element)[0].click();
        });
     });
)};

I have used

$(element).css("background-color", "red");

to see exactly what element jquery is selecting, (I have used capture() to see what is happening on the webpage) and it has selected the correct one. I have tried my code on Firefox's firebug dev tool and it works fine, but I cannot get the click function to work at all.

回答1:

You can try multiple things.

  1. Using the jquery click

    element.click();
    
  2. Using onlick

    element[0].onclick();
    
  3. Using onlick call

    element[0].onclick.call(element[0]);
    
  4. Do a part of this using XPath with casper.click

    var x = require('casper').selectXPath;
    this.evaluate(function(){
        var $element = $('h4:contains("test")').prev().find('.delete');
        $element.css("background-color", "red");
    });
    this.click(x("//h4[contains(.,'test')/preceeding-sibling::*[1]//*[contains(@class,'delete')]]"));