how to display a javascript var in html body

2019-01-12 03:59发布

问题:

I am looking for a way to call a javascript number in the body of an html page. This does not have to be long and extravagant just simply work, I just want something like:

<html>
<head>
<script type="text/javscript">
var number = 123;
</script>
</head>

<body>
<h1>"the value for number is: " + number</h1>
</body>
</html>

回答1:

Try This...

<html>
<head>
<script>
function myFunction() {
    var number = "123";
    document.getElementById("myText").innerHTML = number;
}
</script>
</head>
<body onload="myFunction()">

<h1>"the value for number is: " <span id="myText"></span></h1>

</body>
</html>


回答2:

Use document.write().

<html>
<head>
  <script type="text/javascript">
    var number = 123;
  </script>
</head>

<body>
    <h1>
      the value for number is:
      <script type="text/javascript">
        document.write(number)
      </script>
    </h1>
</body>
</html>



回答3:

You can do the same on document ready event like below

<script>
$(document).ready(function(){
 var number = 112;
    $("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>

or you can simply do it using document.write(number);.



回答4:

<script type="text/javascript">
        function get_param(param) {
   var search = window.location.search.substring(1);
   var compareKeyValuePair = function(pair) {
      var key_value = pair.split('=');
      var decodedKey = decodeURIComponent(key_value[0]);
      var decodedValue = decodeURIComponent(key_value[1]);
      if(decodedKey == param) return decodedValue;
      return null;
   };

   var comparisonResult = null;

   if(search.indexOf('&') > -1) {
      var params = search.split('&');
      for(var i = 0; i < params.length; i++) {
         comparisonResult = compareKeyValuePair(params[i]); 
         if(comparisonResult !== null) {
            break;
         }
      }
   } else {
      comparisonResult = compareKeyValuePair(search);
   }

   return comparisonResult;
}

var parcelNumber = get_param('parcelNumber'); //abc
var registryId  = get_param('registryId'); //abc
var registrySectionId = get_param('registrySectionId'); //abc
var apartmentNumber = get_param('apartmentNumber'); //abc

        
    </script>

then in the page i call the values like so:

 <td class="tinfodd"> <script  type="text/javascript">
                                                    document.write(registrySectionId)
                                                    </script></td>



回答5:

You cannot add JavaScript variable to HTML code.

For this you need to do in following way.

<html>
<head>
<script type="text/javscript">
var number = 123;

document.addEventListener('DOMContentLoaded', function() {
   document.getElementByTagName("h1").innerHTML("the value for number is: " + number);
});
</script>
</head>
<body>
<h1></h1>
</body>
</html>