访问页面时,自动单击页面上的锚链接

时间:2012-05-31 01:43:57

标签: javascript jquery html

之前我问过这个问题,但有些专家告诉我要添加

<meta http-equiv="refresh" content="2;url=http://www.example.com/" />

这可以重新加载给定的链接,但我想知道如何在id的帮助下点击元素(锚)。是否有任何代码在执行时会点击id ='dp99',我希望在访问该页面时执行此javascript。这是HTML

<a id='d99' href='http://someline.com'>This is a link</a>

如果有人能帮助我,我将不胜感激!谢谢。

2 个答案:

答案 0 :(得分:2)

使用jQuery:

$(document).ready(function() { $('#dp99').click(); });

没有jQuery:

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('dp99').click();
});

答案 1 :(得分:0)

http://marcgrabanski.com/articles/simulating-mouse-click-events-in-javascript

function mouseEvent(type, sx, sy, cx, cy) {

  var evt;

  var e = {

    bubbles: true, cancelable: (type != "mousemove"), view: window, detail: 0,

    screenX: sx, screenY: sy, clientX: cx, clientY: cy,

    ctrlKey: false, altKey: false, shiftKey: false, metaKey: false,

    button: 0, relatedTarget: undefined

  };



  if (typeof( document.createEvent ) == "function") {

    evt = document.createEvent("MouseEvents");

    evt.initMouseEvent(type, e.bubbles, e.cancelable, e.view, e.detail,

    e.screenX, e.screenY, e.clientX, e.clientY,

    e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,

    e.button, document.body.parentNode);

  } else if (document.createEventObject) {

    evt = document.createEventObject();

    for (prop in e) {

      evt[prop] = e[prop];

    }

    evt.button = { 0:1, 1:4, 2:2 }[evt.button] || evt.button;

  }

  return evt;

}



function dispatchEvent (el, evt) {

  if (el.dispatchEvent) {

    el.dispatchEvent(evt);

  } else if (el.fireEvent) {

    el.fireEvent(‘on’ + type, evt);

  }

  return evt;

}