简体   繁体   中英

JavaScript window.onload

<!DOCTYPE html>  
<html>  
<head>  

    <script type="text/javascript" >
                 
               function changeTitle() {                      
                  if (document.getElementById('myText').value === "") {                     
                     document.getElementById('title').innerHTML = "Welcome to JavaScript";  
                     alert("Enter a valid text title");  
                     return;                      
                  } else {                        
                  document.getElementById('title').innerHTML = document.getElementById('myText').value;  
                  
                  }  
               }                                
      </script>           
</head>          
<body>  
    <h1 id="title">Welcome to JavaScript</h1>      
    <p> Hello! This is my first JavaScript example on Microsoft Visual Studio Express Edition 2013.</p>          
    <p>  
        <input id="myText" type="text"/>  
        <input type="submit" onclick="changeTitle();" value="Click me!"/>  
    </p>      
</body>  
</html>  

In this little example, I want to save the initial innerHTML of the h1 tag (id=title) to a variable after loading the page for the first time.

And then instead of the document.getElementById('title').innerHTML = 'Welcome to JavaScript' which is inside the if statement, I want to substitute that above mentioned variable with the phrase "Welcome to JavaScript ".

My main intention is, wwhenever some one leaves the textbox ( id=myText ) blank and click on the submit button, script should replace the innerHTML of the h1 tag ( id=title ) to the initial value that was there in the first page load and pop out that alert box. (Maybe user has changed the innerHTML of the h1 before, but the script should replace it to the initial value that was there in the first page load).

You can declare a hidden input.

<input type="hidden" id="initialTitle" value=""/>

and populate the hidden field value via body onload JS function like.

function setInitialTitle() { document.getElementById('initialTitle').value = document.getElementById('title').innerHTML }


<body onload="setInitialTitle()";>

And in changeTitle() function rewrite if block as.

document.getElementById('title').innerHTML = document.getElementById('initialTitle').value;

Just use onload="changeTitle()"

here is a demo: http://jsfiddle.net/nn007/cKk4U/1/

Try this instead of your body tag....

<body onload="changeTitle();">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM