初学JavaScript(js基础)

一、将脚本放在哪里

脚本可以放在html页面的两个位置:
脚本总是需要包围在html标签之间。
1.标签之间(称为头脚本);
2.标签之间(称为体脚本);



  
    
    
    My first javascript
  
  
    
    

//结束javascript,表示后面为html代码

output:

初学JavaScript(js基础)_第1张图片
脚本

二、函数

函数由function加上函数名组成。函数名后面是圆括号,在后面是左花括号。组成函数内容的语句出现在后面的行上,然后在用右花括号结束这个函数。

function saySomething () {
    alert (" Four score and seven years ago")
}

三、使用外部脚本


   
     
       
       
      My second javascript 
    
    
      
      

//在script标签中添加src属性,可以调用.js文件

script2.js代码:

window.onload=writeMessage;  //当窗口完成加载时,运行writeMessage 函数
function writeMessage () {    //创建函数“writeMessage () ”
    document.getElementById ("helloMessage").innerHTML="hello,world";
}

四、向用户发出警告




  
  
  my js page
  


  


script3:

alert("Welcome to my Javascript page!");

output:

初学JavaScript(js基础)_第2张图片
javascript page

五、确认用户的选择(条件语句)

if (confirm("Are you sure you want to do that?")){
  alert("You said yes");
}
else{
    alert("You said no");
}

output:


初学JavaScript(js基础)_第3张图片
conrirme
初学JavaScript(js基础)_第4张图片
then
初学JavaScript(js基础)_第5张图片
else

结构:

if(confirm()){
   alert();    //then部分,表示返回true值时执行的代码;
}
else{
   alert();    //表示返回值为false值时执行的代码;
}

六、提示用户

var ans=prompt("Are you sure you want to do that?","");//var变量关键字;ans变量;prompt询问;用逗号分隔两段信息,向用户询问的问题和默认回答;
if(ans){
  alert("You said "+ans);//返回用户的响应
}
else {
  alert("You refused to answer");//ans为null
}

output:


初学JavaScript(js基础)_第6张图片
prompt
初学JavaScript(js基础)_第7张图片
ans
初学JavaScript(js基础)_第8张图片
null

七、用链接对用户进行重定向

1.以下html页面基于链接队用户进行重定向;




  
  
  Welcome to our site
  


  

Welcome to our site

2.通过重定向功能嵌入在代码中,用户甚至不知道你的脚本干预了链接的行为;

window.onload=initAll;
function initAll(){
  document.getElementById("redirect").onclick=initRedirect;
}

function initRedirect() {
  window.location="welcome.html";
  return false;
}

3.以下时启用了javascript功能的用户将看到的另一个html页面;




  
  
  Our Site
  


  

Welcome to our web site, which features lots of cutting-edge Javascript.

七、使用多级条件

你可能感兴趣的:(初学JavaScript(js基础))