您的位置:首页 > Web前端 > JavaScript

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

2011-08-16 16:47 253 查看
简单的一句话就可以获得到元素的属性值,当然,也可以根据需要直接指定值,

不多说,直接上代码

<!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 onload="a()">

<div id="a" name="aaa" onclick="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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: