欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

根据类名遍历数组的三种方法

程序员文章站 2022-03-21 20:42:07
...

(一)原生js遍历

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<span class="a">微信</span>
		<span class="a">QQ</span>
		<span class="a">微博</span>
		<span class="a">短信</span>
		<button id="btn">点击我触发</button>
	</body>
	<script type="text/javascript">
			var btn = document.getElementById("btn");
			btn.onclick = function(){
				var arr = document.getElementsByClassName("a");
				for(var i=0;i<arr.length;i++){
					console.log("获取到的结果是:"+arr[i].innerText)
				}
			}
    </script>
</html>

(二)jquery的each循环遍历

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<span class="a">微信</span>
		<span class="a">QQ</span>
		<span class="a">微博</span>
		<span class="a">短信</span>
		<button id="btn">点击我触发</button>
	</body>
	<script type="text/javascript">
	    $("#btn").on("click",function(){
		    $(".a").each(function(){
			    console.log($(this).text());
		    })
	    })
    </script>
</html>

(三)jquery的for循环遍历

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<span class="a">微信</span>
		<span class="a">QQ</span>
		<span class="a">微博</span>
		<span class="a">短信</span>
		<button id="btn">点击我触发</button>
	</body>
	<script type="text/javascript">
		$("#btn").on("click",function(){
			var span = $(".a");
				for(var i=0;i<span.length;i++){
					console.log($(".a").eq(i).text());
			}
		});
	</script>
</html>

 

相关标签: 遍历