JS:day02

一、DOM(文档对象模型)

1、获取元素的几种方式

①.通过 id 查找 HTML 元素(getElementById)
<script>
    var one = document.getElementById("two");
    one.onclick=function(){
        this.style.cssText="width:200px;height:200px;border: 10px solid blue;"
    }
</script>
②.通过 class 查找 HTML 元素(getElementsByClassName):数组
<script>
    var one = document.getElementsByClassName("one")[0];
    one.onclick=function(){
        this.style.cssText="width:200px;height:200px;border: 10px solid blue;"
    }
</script>
③.通过标签名查找 HTML 元素(getElementsByTagName):数组
<script>
    var one = document.getElementsByTagName("div")[0];
    one.onclick=function(){
        this.style.cssText="width:200px;height:200px;border: 10px solid blue;"
    }
</script>
④.通过选择器查找 HTML 元素(querySelectorAll):数组
<script>
    var one = document.querySelectorAll(".test")[0];
    one.onclick=function(){
        this.style.cssText="width:200px;height:200px;border: 10px solid blue;"
   }
</script>

2、DOM属性

1、innerHTML 属性
<p id="p">hello world</p>
![](images/down.jpg)
<button id="btn">修改</button>

<script>
    var btn = document.getElementById("btn");
    var p = document.getElementById("p");
    var img = document.getElementById("img");
    btn.onclick=function(){
        p.innerHTML="修改";
        p.style.color="pink";
        img.src="images/icon1.png"
        p.style.cssText = " background-color:red ";
    }
</script>

【在上面的例子中,getElementById 是一个方法,而 innerHTML 是属性。】

二、for循环

for 循环的语法:

for (语句 1; 语句 2; 语句 3) {
            被执行的代码块
  }
<ul>
    <li>hello world</li>
    <li>hello world</li>
    <li>hello world</li>
    <li>hello world</li>
</ul>

<script>
    var li = document.querySelectorAll("ul>li");
    console.log(li.length);
    for(var i=0;i<li.length;i++){
        li[i].onclick=function(){
            this.style.color="pink"
        }
    }
</script>

//    length:长度

例子:for循环乘法表

<script>
    for(var i=1;i<=9;i++){
        for(var n=1;n<=i;n++){
            document.write(i+"*"+n+"="+i*n+"    ");
        }
        document.write("<br>")
    }
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我们首先要明白,我们给页面添加效果用到的js到底是什么?js其实包含三部分:dom 文档对象模型 bom 浏览...
    一直以来都很好阅读 817评论 0 0
  • 个人博客:https://yeaseonzhang.github.io 花了半个多月的时间,终于又把“JS红宝书”...
    Yeaseon阅读 11,594评论 9 52
  • 一、样式篇 第1章 初识jQuery (1)环境搭建 进入官方网站获取最新的版本 http://jquery.co...
    凛0_0阅读 3,466评论 0 44
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,854评论 2 17
  • 01 时隔这么久,回到学校里,在学校的食堂里吃了一顿饭,是平常最爱吃的饺子,顺便点了一碗馄饨,价钱比外面的便宜很多...
    墨离c阅读 632评论 1 2