内容:
-
主要内容:
- Element对象的讲解;
- 对象后给属性名的操作;
- setAttribute方法与getAttribute的使用
-
附加内容:
- removeAttribute方法的使用
运行效果图:
1、内容主界面效果:
2、F12开发者模式Console效果图:
代码片段:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>黑马第67讲代码编辑</title>
<!--用于测试inputx文本框对象是否直接通过inputx.class能否获得值,经过测试发现结果为:undefined-->
<style type="text/css">
.x{margin: 0 auto;}
</style>
</head>
<body>
<input type="text" value="aaaa" id="MyBoxText" class="x"><!--创建一个文本框-->
<!--对id为MyBoxText的文本框进行属性处理操作-->
<script>
var inputx = document.getElementById("MyBoxText");//获取MyBoxText文本框
console.log("inputx的value属性值::"+inputx.value);//inputx对象后可以直接给属性名
console.log("inputx.class"+inputx.class);//这里的inputx对象后边给class属性会出现undefined的结果,<?这是为啥子呢?>
console.log("inputx的id属性值::"+inputx.id);//可得结果
console.log("inputx的type属性值::"+inputx.type);//可得结果
inputx.setAttribute("name","a1");//为inputx对象添加name属性,并添加属性值为"a1"
console.log("inputx的name属性值::"+inputx.getAttribute("name"));//inputx对象后直接跟getAttribute()方法
/**
setAttribute用于接受属性并赋值,getAttribute用于接收对象的属性值
*/
inputx.removeAttribute('name');//用于删除对象控件的属性,这里删除inputx对象的name属性
console.log("inputx.getAttribute('name'):"+inputx.getAttribute('name'));//再次打印inputx对象的name属性时,结果为null
/**
使用getAttribute读取class属性可以获取值吗?请往下看-》》》
*/
console.log("inputx的class属性值::"+inputx.getAttribute('class'));//可得结果
</script>
</body>
</html>
知识点:
- setAttribute( 属性名 , 属性值 )方法给对象添加属性;
- getAttribute( 属性名 )方法用于获取某对象的属性值;
- removeAttribute( 属性名 )方法用于给对象删除属性。
注意事项:
1、部分需要在内或后;<!因为Html代码是浏览器解释执行的,执行顺序是从上到下进行执行!>;
2、如果将部分放在中,inputx对象获取不了MyboxText这个文本框,最终导致代码出错,无法执行。
总结:
1、Element对象可通过直接调用属性获取属性值,但存在某些属性不能获取到值,例如class属性,则返回一个undefined;
2、Element对象通过setAttribute方法添加属性并赋值,利用getAttribute方法调用属性值,此方法可以获取对象的所以属性值,与第一种方法相比,可靠性更高,不易出错。
备注:文章存在一些不足之处,希望大家能指出,谢谢!