javascript基礎學習一
阿新 • • 發佈:2018-11-11
一、
1、= 賦值號
2、== 等於號
3、===
完全等於號(如x=“2”,y=2,如果是x==y是true,若是x===y
,則是flase)
二、var age=15
相當於 window.age=15
三、function sayage( ){
alert( "我"+age);
}
sayage( );
------會出現彈窗顯示我是15
相對於----------------------------------------------------------------
window.sayage=function(){
alert("我"+age);
}
sayage();
------會出現彈窗顯示我是15
四、var message=prompt("請輸入您的星座","天蠍座");
console.log(message);
----------將出現一個“請輸入您的星座的”輸入框,點選確認,則將天蠍座列印到控制檯。
五、刪除(繫結事件)注意:需要將JavaScript寫在HTML語言前面
<body> <div id="box"> <span>蘋果XR</span> <input type="button" id="btn" value="刪除"> </div> </body> <script type="text/javascript">var btn=document.getElementById("btn"); btn.onclick=function(){ var result=window.confirm("您確認要刪除嗎"); if (result) { document.getElementById("box").style.display="none"; } } </script> </html>
若要將JavaScript放到head裡面,則需要將JavaScript的內容裝載到window.onload = function(){ 內容 }
裡面,如下面程式碼:
<head> <script type="text/javascript">var btn=document.getElementById("btn"); window.onload = function(){ btn.onclick=function(){ var result=window.confirm("您確認要刪除嗎"); if (result) { document.getElementById("box").style.display="none"; } }} </script> </head> <body> <div id="box"> <span>蘋果XR</span> <input type="button" id="btn" value="刪除"> </div> </body> </html>
六、視窗關閉window.close
window.onload = function(){
var btn = document.getElementById("btn");
btn.onclick = function(){
window.close();
}
}
</script>
</head>
<body>
<input type="button" id="btn" value="關閉視窗">
</div>
</body>
</html>
七、開啟新視窗window.open
window.onload = function(){
var btn = document.getElementById("btn");
btn.onclick = function(){
window.open("oo.html"); //**開啟oo.html的頁面**
}
}
</script>
</head>
<body>
<input type="button" id="btn" value="開啟新視窗">
</div>
</body>
</html>
八、獲取當前星期
var week=new Date().getDay();(獲取當前日期
switch(week){
case 0:
document.write("星期天");break;輸出當前日期
case 6:
document.write("星期六");break;
}
九、控制提示視窗彈出時間
1)第一種方法
setTimeout("alert('hello')",5000); //5秒後彈出提示視窗
2)、第二中方法
var time=function(){
alert("hello");
}
setTimeout(time,5000);
3)、第三種方法(匿名函式)
var timeout1=setTimeout(function(){
alert("hello");
},2000)
十、清除延時clearTimeout(id )
<script type="text/javascript">
var timeout1=setTimeout(function(){
alert("hello");
},2000)
clearTimeout(timeout1); //清除超時呼叫
</script>
十一、螢幕間歇出現內容
1)第一種方法
var timeout1=setInterval(function(){ //var timeout1=可省略
document.write("我愛你\n");
},1000)
每隔一秒在螢幕出現 我愛你
三個字
2)第二種方法
var timeout1=function() {
document.write("我愛你\n");
}
setInterval(timeout1,500);
十二、在多少時間後停止輸出內容
var timeout1=setInterval(function(){
document.write("我愛你\n");
},1000)
//在2秒後停止輸出
setTimeout(function(){
clearTimeout(timeout1);
},2000)
十三、在螢幕每隔一秒順序輸出1到10,當大於10的時候停止輸出
1)第一種方法
var num=0,max=10,timer;
timer=setInterval(function(){
num++;
if (num>10) {
clearsetInterval(timer);
}
document.write(num+'\n');
},1000);
2)第二種方法
var num=0,max=10,timer;
function bb(){
document.write(num+"\n");
num++;
if (num<max) {
timer=setTimeout(bb,1000);
}else{
clearTimeout(timer);
}
}
timer=setTimeout(bb,1000);