我是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>
- 第二个问题是如何使用onclick函数:
<li class="blue"><a href="#" onclick="incremente()">stuff</a></li>
答案 0 :(得分:1)
您通常会使用具有某种模板的框架来实现此目的。但是,有很多方法可以将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;
将事件添加到节点上的函数use addEventListener
。
el.addEventListener("click", pourcentage.bind(window, 100, 5), false);
答案 1 :(得分:1)
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;
}
&#13;
<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>
&#13;
答案 2 :(得分:-2)
首先,纯javascript很难直接在html中显示变量。如果你想做你喜欢的代码,请检查javascript库(AngularJS或hadlebar)
第二
<html>
...
<script>
function yourFunction() {
//your code in here..
}
</script>
...
<li><a href="#" onclick="yourFunction()">something</a></li>