开发者

Javascript - clicking an image using code

I have an image on a page. I cannot change the page. When you click on the images this page has, a function run and processes the image. The image is not a button. To make the image respond to clicks, the page developer added a listener to it. In fact, every image on that page has a listener. The listener is listening the "img" tag.

When you click on an image, the Javascript checks to see if that image should respond to a click and then runs or not a funct开发者_运维技巧ion.

I am developing some automation to fill the form where this image is. This automation script needs to fill the form and click on that image. How do I click on that image using javascript?

What should I look on the code to discover the method that runs when the image is clicked?

My problem is this: as the listener is attached to all images on that page but just some respond to the clicks, I suppose that the function attached to the listener has to receive a reference to the image that needed to be process... this is what complicates everything...

If you guys want, I can zip the page and the javascripts and put it here.

thanks


http://jsfiddle.net/efortis/9nmAR/

$(document).ready(function (){
    $('img').click(function() {
        alert($(this).attr('alt'));     
    });


$('img').eq(0).click();     // << I think this is what you need

});


Dispatch a click event:

var target = yourImage;  //<--(insert your image here);
if(document.createEvent) {
  //Normal W3C event model
  var clickEvent = document.createEvent("MouseEvents");
  clickEvent.initMouseEvent("click", true, true, window, 
    0, 0, 0, 0, 0, false, false, false, 0, null);
  target.dispatchEvent(clickEvent);
}
else {
  //IE event model
  target.fireEvent("onclick");
}

Normally, clicks are attached to an element using element.addEventListener and element.attachEvent, but sometimes element.onclick is used.
If the page uses jQuery, it might use the live method, which attaches to the root node. However, the previous method should work correctly since the event's target is set to target.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜