简体   繁体   中英

display javascript variable in html code

im really new to javascript and im kind of stuck with two problems :

-first problem: how can i display variables in html code, here's mine:

<script type="text/javascript">
var $first = 1000;
var $seconde = 50;
var $percentage = 0;
function pourcentage(somme, but) {
    percentage = ((somme / but ) * 100);} 
function incremente() {
    $first = $first + 10 ;}   
</script>  

and here's what im trying to do:

 <li><a href="#">first variable $first seconde one is $seconde</a></li>

-2nd problem is how to use a function onclick:

<li class="blue"><a href="#" onclick="incremente()">stuff</a></li>

thank you for your time :)

You would generally use a framework with some sort of templating to accomplish this. However, there are many ways to inject javascript variables into your html. Inside your javascript file or script block:

var $first = 1000;
var $seconde = 50;

//target the element whose html you want to edit
var el = document.getElementById('targetMe');

//use the innerHTML() method of DOM elements to edit the HTML of the targeted element
el.innerHTML = "first variable "+ $first +" second one is "+$seconde;

to add event to a function use addEventListener on a node.

el.addEventListener("click", pourcentage.bind(window, 100, 5), false);

 var $first = 1000; var $seconde = 50; var $percentage = 0; var place1=document.getElementById('first'); var place2=document.getElementById('second'); function pourcentage(somme, but) { percentage = ((somme / but ) * 100); alert('pourcentage = '+percentage+'%'); } function incremente() { $first = $first + 10 ; place1.innerHTML=$first; place2.innerHTML=$seconde; } 
 <a href="#">first variable is <span id="first"></span> and seconde one is<span id="second"></span></a> <br><button onclick="pourcentage(100,5)">pourcentage</button> <br><button onclick="incremente()">incremente</button> 

nice to meet you friend.

first, pure javascript is hard to display variable in html directly. If you want to do like your code, check javascript libraries(AngularJS or hadlebar)

2nd

<html>
...
<script>
function yourFunction() {
  //your code in here..
}

</script>

...

<li><a href="#" onclick="yourFunction()">something</a></li>

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