jQuery 的香草 JavaScript 版本 .click [英] Vanilla JavaScript version of jQuery .click

查看:27
本文介绍了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;
    };
}

这篇关于jQuery 的香草 JavaScript 版本 .click的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆