I have this script for testing the jquery click() capability within phantomJS.
var page = require('webpage').create(),
address;
address="https://jsfiddle.net/t8atxcfL/";
page.onConsoleMessage = function(msg) {
console.log('eval- ' + msg);
};
page.open(address, function(status){
if(status==="success"){
console.log("Page loaded");
page.viewportSize={width:1920, height:1080};
page.render("before.png");
page.includeJs("//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function(){
console.log("executing jquery");
var toFocus = page.evaluate(function(){
console.log("getting iframe name...")
return document.getElementsByTagName("iframe")[0].name;
});
page.switchToFrame(toFocus);
page.evaluate(function() {
console.log($("#par").text());
$("#par").click();
console.log($("#par").text());
});
page.viewportSize={width:1920, height:1080};
page.render("after.png");
phantom.exit();
});
}
});
This version seems to work fine, the output being:
user@home$ phantomjs chooseframe.js
Page loaded
executing jquery
eval- getting iframe name...
eval-
Before clicking...
eval- I was clicked
The problem is when I replace $("#par").click();
with $("#par").click(function(){console.log("I am now clicking")});
Then, the output becomes
user@home$ phantomjs chooseframe.js
Page loaded
executing jquery
eval- getting iframe name...
eval-
Before clicking...
eval-
Before clicking...
The issue is that even if the callback function is empty, like $("#par").click(function(){});
and even if I remove the phantom.exit()
line the output stays the same no matter how long I wait.
Could anybody please tell me how to make .click()
work the intended way, or why it could not work?
答案 0 :(得分:1)
$("#par").click();
triggers the existing click handler for the link, whereas your later example sets a new click handler, but doesn't click the element to trigger the click handler.
Simply make sure you click after adding the click handler:
$("#par").click(function() {
console.log("I am now clicking");
});
$("#par").click();