How to add click event to an element?(如何将点击事件添加到元素?)
问题描述
我想用纯 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.
这篇关于如何将点击事件添加到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将点击事件添加到元素?


- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01