JavaScript - Common uses

About javaScript

 

The first JavaScript program: 

     Click the button to display the date  

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
function displayDate(){
    document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>

<h1>h1</My first JavaScript program> 
< P ID = "Demo" > This is a paragraph </ P > 

< Button type = "Button" the onclick = "displayDate ()" > DATE </ Button > 

</ body > 
</ HTML >

 

 Common uses javaScript

HTML can be directly written to the output stream in which:

< P > 
the JavaScript HTML can be written directly to the output stream: 
</ P > 
< Script > 
document.write ( " <h1 of> This is a header </ h1 of> " ); 
document.write ( " <P> This is a <strong> paragraph </ strong> </ P>. " );
 </ Script > 
< P > 
You can use only HTML output stream < strong > document.write </ strong > . 
If you use it after the document has loaded (for example, in a function), will cover the entire document. 
</ P >

 

 React to events

< The Button of the type = "the Button" onclick = "Alert ( 'Welcome!')" > Point me! </ The Button >

————> 

 

 

Change the contents of an HTML element

< The p- the above mentioned id = "Demo" > 
JavaScript to change the content of the HTML element. 
</ P > 
< Script > 
function myFunction () 
{ 
    X = document.getElementById ( " Demo " );   // find the elements 
    x.innerHTML = " the Hello the JavaScript! " ;     // change the content 
}
 </ Script > 
< Button type = "the Button" onclick = "myFunction ()" > click here <

————>  

 

 

 

 HTML image change

<script>
function changeImage()
{
    element=document.getElementById('myimage')
    if (element.src.match("bulbon"))
    {
        element.src="/images/pic_bulboff.gif";
    }
    else
    {
        element.src="/images/pic_bulbon.gif";
    }
}
</script>
<img id="myimage" onclick="changeImage()" src="/images/pic_bulboff.gif" width="100" height="180">

————>  

 

 

 

Change the HTML element styles

<p id="demo">
JavaScript 能改变 HTML 元素的样式。
</p>
<script>
function myFunction()
{
    x=document.getElementById("demo") // 找到元素
    x.style.color="#ff0000";          // 改变样式
}
</script>
<button type="button" onclick="myFunction()">点击这里</button>

  ——————>   

 

 

 验证输入

<p>请输入数字。如果输入值不是数字,浏览器会弹出提示框。</p>
<input id="demo" type="text">
<script>
function myFunction()
{
    var x=document.getElementById("demo").value;
    if(x==""||isNaN(x))
    {
        alert("不是数字");
    }
}
</script>
<button type="button" onclick="myFunction()">点击这里</button>

 

Guess you like

Origin www.cnblogs.com/expedition/p/11028485.html