如何将点击事件添加到元素? [英] How to add click event to an element?

查看:29
本文介绍了如何将点击事件添加到元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用纯 JavaScript(不使用 jQuery)向这样的元素添加一个点击事件,所以我没有 id 而是一个类:

I would like to add a click event in plain JavaScript (without using jQuery) to an element like this, so I don't have an id but a class:

<a href="http://example.com/share" class="MyClass">Yummy</a>

推荐答案

如果你没有 id 并且没有任何选择器库,并且希望它在旧浏览器中工作,那么它需要更多的工作.如果你能在上面加上一个id,那就很简单了.如果没有,则需要更多代码:

If you don't have an id and don't have any selector library and you want it to work in older browsers, then it takes a bit more work. If you can put an id on it, it's quite simple. If not, it takes more code:

var links = document.getElementsByClassName("MyClass");
links[0].onclick = function() {
    // put your click handling code here
    // return(false) if you don't want default click behavior for the link
}

由于 getElementsByClassName 在旧版浏览器中并非普遍可用,因此您需要一个 shim 来在不存在时实现它.或者,您可以通过以下方式获取文档中的所有链接:

Since getElementsByClassName is not universally available in older browsers, you would need a shim to implement it when not present. Or, you could get all the links in your document with:

var links = document.getElementsByTagName("a");

然后循环浏览该列表,直到找到您想要的(可能检查类名).

and then cycle through that list until you find the one you want (perhaps checking the class name).

如果你可以在链接上放一个ID:

If you can put an ID on the link:

<a href="http://braza.com/share" id="specialLink" class="MyClass" >Yummy</a>

然后,它只需要以下代码:

Then, it just takes this code:

document.getElementById("specialLink").onclick = function() {
    // add code here
}

如果您要定期执行此操作,则添加事件侦听器比使用 onclick 属性更具可扩展性,但如果您没有任何框架,那么您需要一个用于添加事件侦听器的函数处理旧版本的 IE.

If you're going to do this regularly, the adding an event listener is a little more extensible than using the onclick property, but if you don't have any framework, then you need a function for adding an event listener that handles older versions of IE.

这篇关于如何将点击事件添加到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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