Vanilla JavaScript version of jQuery .click

喜你入骨 提交于 2019-11-28 04:38:42
Kevin Bowersox

Working Example: http://jsfiddle.net/6ZNws/

Html

<a href="something">CLick Here</a>
<a href="something">CLick Here</a>
<a href="something">CLick Here</a>

Javascript:

var anchors = document.getElementsByTagName('a');
for(var z = 0; z < anchors.length; z++) {
    var elem = anchors[z];   
    elem.onclick = function() {
        alert("hello");
        return false;
    };
}
element.addEventListener('click', function() { ... }, false);

You have to locate the elements and make a loop to hook up each one.

Try the following

var clickHandler = function() { 
  // Your click handler
};

var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
  var current = anchors[i];
  current.addEventListener('click', clickHandler, false);
}

Note: As Ӫ_._Ӫ pointed out this will not work on IE8 and lower as it doesn't support addEventListener.

On IE8 you could use the following to subscribe to onclick. It's not a perfect substitute as it requires everyone to be cooperative but it may be able to help you out

var subscribeToOnClick = function(element) {
  if (element.onclick === undefined) {
    element.onclick = clickHandler;
  } else {
    var saved = element.onclick;
    element.onclick = function() {
      saved.apply(this, arguments);
      clickHandler.apply(this, arguments);
    }
  }
}

for (var i = 0; i < anchors.length; i++) {
  var current = anchors[i];
  subscribeToOnClick(current);
}
document.getElementById('elementID').onclick = function(){
      //click me function!
}

Here you go:

[].forEach.call( document.querySelectorAll( 'a' ), function ( a ) {
    a.addEventListener( 'click', function () {
        // code here
    }, false );
});

Live demo: http://jsfiddle.net/8Lvzc/3/

(doesn't work in IE8)

Also, I recommend event delegation...

This will assign an onclick function to every a element.

var links = document.getElementsByTagName("a");
var linkClick = function() {
  //code here
};

for(var i = 0; i < links.length; i++){
  links[i].onclick = linkClick;
}

You can see it in action here.

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