javascript 小demo

1. textContent用法

document.getElementById('button1').onclick=function button1(){
        var a=parseInt(document.getElementById('num1').value);
        var b=parseInt(document.getElementById('num2').value);
        document.getElementById('sum').textContent=a+b
    }

2.return用法

function sum(num){
    var prise=50;
    total=num*prise
    return total
}
var a=sum(10)
console.log(a)  //500

3. if else if

var hungry =2
function eat(food){
    console.log(
        '我想吃'+food
    )
}
if (hungry <=3){
    eat('西红柿鸡蛋面')
   
}
else if(hungry>3 && hungry <=7){
    eat('玉米')}


else{
    console.log('我不想吃东西')
}

4 .for····break

var shuzu=[
    {
        framer:'李静',
        id:001,
        sheep:22,
        horse:10,

    },
    {
        framer:'Danny',
        id:002,
        sheep:10,
        horse:9,

    },
    {
        framer:'KK',
        id:003,
        sheep:67,
        horse:20,

    },
    {
        framer:'Lily',
        id:004,
        sheep:30,
        horse:30,

    },
    {
        framer:'Lily',
        id:005,
        sheep:10,
        horse:20,

    }
]



for( var i=0;i<shuzu.length;i++){
    if(shuzu[i].sheep>20){
        console.log(shuzu[i].framer+'的农场的绵羊刚好够20只')
    }
   break;

}

加上break

加上break.png

不加break
不加break.png

5.点击按钮,更换div的样式

<style>
    #change{
      width: 300px;
      height: 300px;
      background-color: blue;
    }
    #changeDiv{
      width: 300px;
      height: 300px;
      background-color:red;
    }
  
  </style>

<button id="btn"  onclick='change()'>change Red</button>
<div id="change"></div>
<script>
var el=document.querySelector('#btn')
var changeDiv = document.querySelector('#change')
var a=false;
function change (){
    a=!a
console.log(a)
   if(a==true){
    changeDiv.setAttribute('id','changeDiv')
  var str='dian'
  changeDiv.textcontent=str
  
  }
   else{
     changeDiv.setAttribute('id','change')

  }

}
</script>

5.addEventListener事件监听之true和false

<style>
    #box{
      width: 300px;
      height: 300px;
      background-color: blue;
    }
    #big{
      width: 900px;
      height: 900px;
      background-color:red;
    }
  </style>




<body id="body">
   <div id="big">
  <div id="box"></div>
</div>
</body>





<script>
var elbox=document.querySelector('#box')
elbox.addEventListener('click',function(){
    alert('box')
    console.log('box')

},true)


var elbig=document.querySelector('#big')
elbig.addEventListener('click',function(){
    alert('big')
},false)


var elbody=document.querySelector('#body')
elbody.addEventListener('click',function(){
    alert('body')
},false)
</script>
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容