Triggering click event on anchor tag doesn't works

戏子无情 提交于 2019-11-26 17:24:20

问题


I just ran into this question

FIDDLE

Triggering click event on anchor tag is not working here.

<a class="button2" href="#popup1">hello</a>
<div id="popup1" class="overlay">
  <div class="popup">
    <div class="contentSpec">
      <h2>Would you like to visit</h2>
      <h1>someURL</h1>
    </div>
    <a class="close" href="#"></a>
    <div class="content">

      <div class="box">
        <a class="button" href="#popup1">YES</a>
        <a class="button1" href="#popup1">NO</a>
      </div>
    </div>
  </div>
</div>

JS:

$(document).ready(function() {
  $(".button2").trigger('click');
});

My question, is why the trigger event is not working in this case?


回答1:


You need to call native DOM click() method in order to fire default clicking anchor behaviour, jQuery specifically excludes it on anchor:

$(document).ready(function() {
  $(".button2")[0].click();
});

-jsFiddle-




回答2:


Use

$(".button2").get(0).click();

The get(0) will return the first DOM object instead of the jquery object, and click() will be triggered.

Updated fiddle




回答3:


As you don't have any .click() event bound on it, it never fires it.

You need to fire the DOM click event with .click() instead of .trigger(e) of jQuery method and this should only work on dom nodes. Which you can achieve by introducing the index [0] or with jQuery's method .get(0).

Instead try this:

$(document).ready(function() {
  $(".button2")[0].click();
  // or $(".button2").get(0).click();
});

and if this is the case then you can do this with javascript only:

window.addEventListener('DOMContentLoaded', function(e){
   document.querySelector('.button2').click();
}, false);


来源:https://stackoverflow.com/questions/34174134/triggering-click-event-on-anchor-tag-doesnt-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!