问题描述
我想在纯JavaScript(不使用jQuery)中添加一个click事件到这样的元素,所以我没有 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,那就很简单了。如果没有,则需要更多代码:
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
不是在旧浏览器中普遍可用,当不存在时,您需要垫片来实现它。或者,您可以获取文档中的所有链接:
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.
这篇关于如何将click事件添加到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!