使用js获得元素的属性值及事件名

 简单的一句话就可以获得到元素的属性值,当然,也可以根据需要直接指定值,

不多说,直接上代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <script type="text/javascript">
  function a(){
        var s=document.getElementById("a").attributes.getNamedItem("name").nodeValue;
        alert("name的属性值"+s);  <!--结果为“name的属生值aaa”-->
        var s2=document.getElementById("a").attributes.onclick.value;
        alert("onclick的事件名"+s2); <!--结果为“onclick的事件名fn()”-->

  }

function fn(){

}
  </script>
 </head>

 <body οnlοad="a()">
  <div id="a" name="aaa" οnclick="fn()">ccc</div>
 </body>
</html>

当然还有其他一些方法获得属性值,多了解一下js的attributes,其实这是一个很强大的东东。

还可以使用以下的方法,在IE和火狐下都可以使用。

以下是转载的。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>获取元素属性</title> 
</head> 
<body> 
<div id="roboth"></div> 
<script type="text/javascript"> 
//<![CDATA 
//attributes elements NamedNodeMap 
var div=document.getElementById("roboth"); 
alert(div.attributes.getNamedItem("id").nodeValue); 
alert(div.attributes.item(0).nodeValue); 
alert(div.getAttributeNode("id").nodeValue); 
alert(div.getAttribute("id")) 
//]]> 
</script> 
</body> 
</html> 

猜你喜欢

转载自blog.csdn.net/salonzhou/article/details/6692239
今日推荐