jQuery 的香草 JavaScript 版本 .click

所以也许我只是没有在正确的地方寻找,但我找不到一个很好的解释来说明如何做相当于 jQuery 的操作

So maybe I'm just not looking in the right places but I can't find a good explanation of how to do the equivalent of jQuery's

$('a').click(function(){
    // code here
});

在普通的旧 JavaScript 中?

in plain old JavaScript?

基本上我想在每次单击 a 标记时运行一个函数,但我没有能力将 jQuery 加载到页面中以按上述方式执行此操作,所以我需要知道如何使用纯 JavaScript 来做到这一点.

Basically I want to run a function every time an a tag is clicked but I don't have the ability to load jQuery into the page to do it in the way above so I need to know how to do it using plain JavaScript.

推荐答案

工作示例:http://jsfiddle.net/6ZNws/

HTML

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

Javascript:

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;
    };
}

相关文章