使用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 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>
相关文章推荐
- 2017.7.14 学习笔记 JQ选择器的使用及JS输入框事件及获取其相对属性值
- JS中批量给元素绑定事件过程使用闭包解决
- HTML5 audio元素如何使用js与jquery控制其事件
- js中获取同名的元素--使用getElementsByName()函数获得数组
- JS中批量给元素绑定事件过程中的相关问题使用闭包解决
- JS中批量给元素绑定事件过程中的相关问题使用闭包解决
- HTML5 audio元素如何使用js与jquery控制其事件
- 使用js写点击一个事件使页面返回顶部以及控制一个元素在右下角的固定位置的方法
- 使用js给元素添加事件
- AngularJS 使用元素与事件指令
- 使用vue点击li,获取当前点击li父辈元素的属性值
- jquery使用append动态增加元素,该元素绑定事件失效的解决办法
- js之onload事件的一点使用心得
- JQuery中根据属性或属性值获得元素
- 使用js为button添加回车执行事件
- JS 防止父元素事件冒泡触发
- JQuery中根据属性或属性值获得元素
- js动态加载html,加载后的页面元素某些事件失效的解决方案
- JS注册事件 JS:attachEvent和addEventListener 使用方法
- js移除元素所有click绑定事件