<div>这是div</div>
<div>这是div</div>
<div>这是div</div>
<p>这是p</p>
<p>这是p</p>
<p>这是p</p>
<script>
var getTag = 10;
var dvObjs = 20;
var pObjs = 30;
//此处如果不加沙箱,在调用getTag方法的时候会报not function错误,原因是getTag()这个函数会被提升到script代码块的最前面
(function () {
//根据标签名字获取元素
//自调用函数中的函数是私有的,在外部不可以被访问
function getTag(tagName) {
return document.getElementsByTagName(tagName)
}
//获取所有的div
var dvObjs = getTag("div");
for (var i = 0; i < dvObjs.length; i++) {
dvObjs[i].style.border = "2px solid pink";
}
//获取所有的p
var pObjs = getTag("p");
for (var i = 0; i < pObjs.length; i++) {
pObjs[i].style.border = "2px solid pink";
}
}());
console.log(getTag);
console.log(dvObjs);
console.log(pObjs);
</script>