How to call a JavaScript function within an HTML body

后端 未结 4 665
我在风中等你
我在风中等你 2020-12-08 18:41

I have a JavaScript function that fills a table:



        
相关标签:
4条回答
  • 2020-12-08 18:46

    Just to clarify things, you don't/can't "execute it within the HTML body".

    You can modify the contents of the HTML using javascript.

    You decide at what point you want the javascript to be executed.

    For example, here is the contents of a html file, including javascript, that does what you want.

    <html>
      <head>
        <script>
        // The next line document.addEventListener....
        // tells the browser to execute the javascript in the function after
        // the DOMContentLoaded event is complete, i.e. the browser has
        // finished loading the full webpage
        document.addEventListener("DOMContentLoaded", function(event) { 
          var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below  $500.00" ];
          var col2 = ["None", "None", "$8.00"];
          var TheInnerHTML ="";
          for (var j = 0; j < col1.length; j++) {
            TheInnerHTML += "<tr><td>"+col1[j]+"</td><td>"+col2[j]+"</td></tr>";
        }
        document.getElementById("TheBody").innerHTML = TheInnerHTML;});
        </script>
      </head>
      <body>
        <table>
        <thead>
          <tr>
            <th>Balance</th>
            <th>Fee</th>        
          </tr>
        </thead>
        <tbody id="TheBody">
        </tbody>
      </table>
    </body>
    

    Enjoy !

    0 讨论(0)
  • 2020-12-08 19:02

    Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

    0 讨论(0)
  • 2020-12-08 19:06

    Try wrapping the createtable(); statement in a <script> tag:

    <table>
            <tr>
                <th>Balance</th>
                <th>Fee</th>
    
            </tr>
            <script>createtable();</script>
    </table>
    

    I would avoid using document.write() and use the DOM if I were you though.

    0 讨论(0)
  • 2020-12-08 19:10

    First include the file in head tag of html , then call the function in script tags under body tags e.g.

    Js file function to be called

    function tryMe(arg) {
        document.write(arg);
    }
    

    HTML FILE

    <!DOCTYPE html>
    <html>
    <head>
        <script type="text/javascript" src='object.js'> </script>
        <title>abc</title><meta charset="utf-8"/>
    </head>
    <body>
        <script>
        tryMe('This is me vishal bhasin signing in');
        </script>
    </body>
    </html>
    

    finish

    0 讨论(0)
提交回复
热议问题