Browser-friendly way to simulate anchor click with jQuery?

匆匆过客 提交于 2019-11-30 10:46:56

This should work...

$(function() {

  fireClick($("a")[0]);

});

function fireClick(elem) {
  if(typeof elem == "string") elem = document.getElementById(objID);
  if(!elem) return;

  if(document.dispatchEvent) {   // W3C
    var oEvent = document.createEvent( "MouseEvents" );
    oEvent.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1, false, false, false, false, 0, elem);
    elem.dispatchEvent(oEvent);
  }
  else if(document.fireEvent) {   // IE
    elem.click();
  }    
}

Use $('a').click();

I tested this in Chrome and Firefox but don't have an IE handy. This should work transparently in most scenarios.

$('a').live('click.simclick', function(event){
    var $a = $(event.target)
    setTimeout(function(){
        if (event.isPropagationStopped())
            return

        $('<form/>')
            .attr({
                method: 'get',
                target: $a.attr('target'),
                action: $a.attr('href')
            })
            .appendTo(document.body)
            .submit()

             // clean up in case location didn't change
            .remove()
    }, 0)
})

// test it
$('a').eq(0).click()

I use this approach. Seems to work okay.

$(function() {
    fireClick($("a"));
});

function fireClick (elem) {
    window.location = $(elem).attr('href');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!