我想在普通的JavaScript添加点击事件(不使用jQuery),以这样的元素,所以我没有一个id
而是一个类:如何将点击事件添加到元素?
<a href="http://example.com/share" class="MyClass">Yummy</a>
我想在普通的JavaScript添加点击事件(不使用jQuery),以这样的元素,所以我没有一个id
而是一个类:如何将点击事件添加到元素?
<a href="http://example.com/share" class="MyClass">Yummy</a>
如果你没有一个ID并没有任何选择器库,并且你希望它在旧版浏览器中工作,那么它需要更多的工作。如果你可以在它上面加一个id,那很简单。如果不是这样,它需要更多的代码:
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
是不是在旧的浏览器普遍可用的,你需要一个垫片,当不存在实现它。或者,你可以得到所有的链接文档中有:
var links = document.getElementsByTagName("a");
,然后循环通过列表,直到你找到你想要的(也许是检查类名称)之一。
如果你可以把一个ID链接:
<a href="http://braza.com/share" id="specialLink" class="MyClass" >Yummy</a>
然后,它只是需要这样的代码:
document.getElementById("specialLink").onclick = function() {
// add code here
}
如果你要经常做到这一点,添加事件监听器比使用onclick属性更具扩展性,但如果您没有任何框架,那么您需要添加一个处理旧版IE的事件侦听器的函数。
可以有几种方法来做到这一点。
一个是你的权利锚
如添加单击事件:<a href='' onclick='yourFunct()'> Yummy </a>
的另一种方法可以使用document.getElementsByTagName(“A”)就可以得到参考所有的HREF的作为阵列那么你可以选择这个特定的href并添加click事件。
,如:document.getElementsByTagName('a')[0].click = function(){ }
这里0,如果你知道在你数组可以给该索引的确切地点是只是象征。
第三种方式可以是你可以写一个自定义。在javascript中使用document.getElementsByClassName函数并且使用它。您可以通过搜索谷歌找到getElementsByClassName的一些实现。
看看http://robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/的实现之一。
像下面
<a href="http://braza.com/share" class="MyClass" onclick='return somefunction()'>Yummy</a>
<script>
function somefunction()
{
// do your stuff.
// return true, if you want to open the link, or false to cancel
return true;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Untitled</title>
<style type="text/css">
td { border: 1px solid #ccc; }
.findMe { color: gold; }
.youFoundMe { color: green; }
</style>
<script type="text/javascript"><!--
var aryClassElements = new Array();
function doSomething() {
aryClassElements.length = 0;
getElementsByClassName('findMe', document.body);
for (var i = 0; i < aryClassElements.length; i++) {
aryClassElements[i].className = 'youFoundMe';
}
}
function getElementsByClassName(strClassName, obj) {
if (obj.className == strClassName) {
aryClassElements[aryClassElements.length] = obj;
}
for (var i = 0; i < obj.childNodes.length; i++)
getElementsByClassName(strClassName, obj.childNodes[i]);
}
//--></script>
</head>
<body onload="doSomething();">
<h1>Heading 1</h1>
<div>
This code is inside my div.
<span>This code is inside a span inside the div. <a href="#" class="findMe">Link inside the span inside the div.</a></span>
<a href="#">Link inside the div.</a>
</div>
<p>
<h2 class="findMe">My Paragraph's Heading 2</h2>
<table>
<tr>
<td class="findMe">My first cell.</td>
<td>My second cell. <a href="#" class="findMe">Link inside the cell inside the row inside the table.</a></td>
</tr>
</table>
</p>
</body>
</html>`
在这里,你简单的使用是一些代码,可以帮助你。 –