jQuery 以编程方式单击具有 javascript:void(0) 的标签

jQuery programatically click a tag that has javascript:void(0)

我正在尝试以编程方式在页面上点击 "zoom in" 图标三次。 <a> 的结构是:

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

我有以下代码,在文档准备好时调用:

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

我收到循环工作的警报,但缩放功能不工作,不确定如何修复或更好的方法来解决这个问题?

<a href="javascript:void(0)"> 是一种 hack,用于使某些内容可点击,但不会将用户移动到新页面。它与您的缩放功能没有任何关系。

您很可能正在使用某种库或插件来使图像可缩放。您应该阅读文档,看看您的库是否提供了一种以编程方式触发缩放的方法。

你的点击事件触发方式不对

改为使用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.

因此,将其更改为:

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

至:

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

例子:

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>

More reading:

jQuery's event handling system is a layer on top of native browser events. When an event handler is added using .on( "click", function() {...} ), it can be triggered using jQuery's .trigger( "click" ) because jQuery stores a reference to that handler when it is originally added.

Additionally, it will trigger the JavaScript inside the onclick attribute.

The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.