duanhai1455
2015-01-19 21:05
浏览 173

在html代码中显示javascript变量

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanbei7035 2015-01-19 21:15
    已采纳

    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>

    </div>
    
    已采纳该答案
    打赏 评论
  • dongse5408 2015-01-19 21:10

    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);
    
    打赏 评论
  • doudang2817 2015-01-19 21:15

    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>
    
    打赏 评论