问题描述:

I am trying to programmatically click the "zoom in" icon three times on a page. The <a> is structured:

<a class="get-plus" title="zoom in" href="javascript:void(0)" style="display: inherit;">&nbsp;</a>

I have the following code, called on document ready:

function zoomIn() {

// Zoom in

for (var i = 0; i < 3; i++) {

$('a.get-plus').trigger('click');

alert(i);

}

}

I get the alerts that the loop works, but the zoom functionality isn't working, not sure how to fix or a better way to go about this?

网友答案:

Your way to trigger the click event doesn't work.

Instead use HTMLElement.click():

The HTMLElement.click() method simulates a mouse-click on an element.

When click() is used with supported elements (e.g. one of the types), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events. One exception: The click() method will not cause an element to initiate navigation as if a real mouse-click had been received.

Therefore, change it from:

$('a.get-plus').trigger('click');

to:

$('a.get-plus').get(0).click();

The example:

function zoomInChanged() {
  // Zoom in
  for (var i = 0; i < 3; i++) {
    setTimeout(function () {
      $('a.get-plus').get(0).click();
    }, i * 1000);
  }
}

function zoomIn() {
  // Zoom in
  for (var i = 0; i < 3; i++) {
    $('a.get-plus').trigger('click');
    console.log(i);
  }
}

console.log('zoomIn:');
zoomIn();
console.log('zoomInChanged:');
zoomInChanged();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<a class="get-plus" title="zoom in" href="javascript:console.log('Clicked')" style="display: inherit;">&nbsp;</a>
网友答案:

<a href="javascript:void(0)"> is a hack used to make something clickable, but not move the user to a new page. It is in no way related to your zoom functionality.

You're most likely using some sort of a library or plugin to make images zoomable. You should read the docs, and see if you library provides a way to programmatically trigger zooming.

相关阅读:
Top