Triggering click on a link doesn't change location hash

爱⌒轻易说出口 提交于 2020-01-03 15:21:34

问题


I'm working on a web application that uses onHashChange event listener in some situations and manually clicking on a link with href="#hash" works perfectly well. But when I trigger click on the same link using jQuery's $('a[href=#"hash"]').trigger('click') or $('a[href=#"hash"]').click() hash in address bar is not changing.

Is it something that I'm doing wrong? or I shoud use another method for this purpose?

HTML

<a href="#hash">Do Something</a>

JS

// Not working
$('a[href="#hash"]').click();

// Not working
$('a[href="#hash"]').trigger('click');

回答1:


What you wrote is true (it's enough to debug jQuery source code): the trigger click event doesn't work on an anchor.

In order to achieve what you are trying you can get the dom element and then fire the click:

$('a[href="#hash"]').get(0).click()

This only will work.




回答2:


New guy here hopefully not making an azz of himself. I just thought maybe something in this code I'm using on my site might help you. It kinda seems similar to what you're describing.

$(document).ready(function(){
  $('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
      'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
      window.location.hash = target;
    });
  });
   });



回答3:


The click method (when used by jquery) triggers the click events that you register using the el.click(function.. and el.on('click', function...

You can create a new MouseEvent and dispatch it directly to the relevant element:

e = document.createEvent('MouseEvents');
e.initEvent("click", true, true);
$('a[href="#hash"]')[0].dispatchEvent(e)

The above code will work in Chrome, Firefox and IE

Or just use the click event of the element (which will not use jquery's click function, but the browser's click function):

$('a[href="#hash"]')[0].click()

Note that this code might not work in several browsers due to security reasons.



来源:https://stackoverflow.com/questions/41447327/triggering-click-on-a-link-doesnt-change-location-hash

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