2021-11-16 setAttribute()方法的定义和用法,使用setAttribute对元素进行属性设置和其他常见使用场景

文章目录

        • 定义
        • 语法
        • 使用场景一:点击改变input文本框成为一个button按钮
          • 代码
          • 改进:value也用setAttribute设置
        • 使用场景二:使用setAttribute()方法取消类名
        • 使用场景三:使用setAttribute()方法和getAttribut()方法,解决for循环中无法获取自增中的i的bug

定义

setAttribute()方法是用于创建或者改变元素的某个新属性
(若指定属性已经存在,那么仅仅设置其属性值)

语法
element.setAttribute(name,value),

其中:

  • element:div元素
  • name,必选项,是给div元素设置的属性名称
  • value:必选项,是给该属性赋予的属性值
使用场景一:点击改变input文本框成为一个button按钮
代码
<body>
	<input type="text" value="我是input框">
	<button onclick="fn()">点击button>
body>
<script>
	var input=document.getElementsByTagName("input")[0];
	console.log(input.value);
		input.setAttribute("type","button");
	}
script>

结果:点击后input框变成了button按钮

<input type="button" value="我是input框">
改进:value也用setAttribute设置
<body>
	<input type="text" id="input">
	<button onclick="fn()">点击button>
body>
<script>
	var input=document.getElementsByTagName("input")[0];
	console.log(input.value);
	function fn(){
		input.setAttribute("value","点我");
		input.setAttribute("type","button");
	}	
script>
使用场景二:使用setAttribute()方法取消类名
<body>
	<div class="one">hellodiv>
	<button onclick="fn2()">点我取消类名button>
body>
<script>
	var div=document.querySelector(".one");
	console.log("我还有类名:",div);
	function fn2(){
		div.setAttribute("class","");
		console.log("我没有类名了:",div);
	}
script>

结果:
在这里插入图片描述

使用场景三:使用setAttribute()方法和getAttribut()方法,解决for循环中无法获取自增中的i的bug
<body>
	<ul>
		<li>11111</li>
		<li>22222</li>
		<li>33333</li>
	</ul>
</body>
<script>
	for(var i=0;i<lis.length;i++){
		// 	lis[i].οnclick=function(){
		// 		console.log(i);
		// 	}
		lis[i].setAttribute("index",i)
		lis[i].onclick=function(){
			console.log(this.getAttribute("index"));
		}
	}
</script>

你可能感兴趣的:(笔记,知识点,javascript,js,setAttribute,getAttribute,css)