Detailed explanation of three reference modes of js in HTML

  • 2021-08-09 06:46:36
  • OfStack

1. Inline Styles

There are two types of inline styles. 1 is written directly to the inside of the label of the element


<html>
  <title>js Style inline writing </title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <body>
  <!--js Inline writing 01 Begin -->
    <!-- When the mouse clicks on the picture, the pop-up window will pop up and display 1223-->
    <div class="img">
     Click Event: 
      <img src="images/001.jpg" onclick="alert(1223)"></img>
    </div>
  <!--js Inline writing 01 End -->
  </body>
</html>

2 is written to the < script > < /script > In the label

Add id to the element

Through getElementById ('XX'); Method to navigate to the element and add a trigger event to the element

Note: < script > < /script > Labels should be placed in < /body > After


<html>
  <title>js Style inline writing </title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <body>
  <!--js Inline writing 02 Begin -->
  <div class="img">
     Click Event: 
      <img src="images/002.jpg" id='yuansu'></img>
  </div>
  <!--js Inline writing 02 End -->
  </body>
  <script>
    //js Code 
    // Find XX Element, 1 Add elements in a general way id 
    yuansuojb=document.getElementById('yuansu');    
    // To xx Element plus event 
    yuansuojb.onclick=function(){
      // Code snippet 
      alert(1);
    }
    // Trigger event 
  </script>
</html>

2. Outreach style

Write the code of js to the file of. js and refer to it in HTML

The. html file reads as follows:


<html>
  <title>js Style outreach writing </title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <body>
  <div class="img">
     Outreach writing -- Click Event: 
      <img src="images/003.jpg" id='yuansu'></img>
  </div>
  </body>
  <script src='js/index.js'></script>
</html>

The. js file reads as follows:


//js Code 
// Find XX Element, 1 Add elements in a general way id 
yuansuojb=document.getElementById('yuansu');    
// To xx Element plus event 
yuansuojb.onclick=function(){
  // Code snippet 
  var str="hello world !!!";
  alert(str);
}

Related articles: