在 HTML 代码中显示 JavaScript 变量


display javascript variable in html code

我真的是Javascript的新手,我有点卡在两个问题上:

-第一个问题:如何在 HTML 代码中显示变量,这是我的:

<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>  

这就是我试图做的:

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

-第二个问题是如何使用点击函数:

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

感谢您抽出宝贵时间:)

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>

您通常会使用带有某种模板的框架来完成此操作。 但是,有很多方法可以将javascript变量注入到html中。在您的 JavaScript 文件或脚本块中:

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;

若要向函数添加事件,请在节点上使用addEventListener

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

很高兴认识你的朋友。

首先,纯JavaScript很难直接在HTML中显示变量。如果你想像你的代码一样做,检查javascript库(AngularJS或hadlebar)

第二

<html>
...
<script>
function yourFunction() {
  //your code in here..
}
</script>
...
<li><a href="#" onclick="yourFunction()">something</a></li>