سؤال

I need to multiply a number with the values 1 till 64. I want to make this better by just selecting the number through a given selection, but somehow it only takes the first value of my selection. What is wrong here?

<body>
<h1>some calculation</h1>
<script type="text/javascript">
    function times(wert) {
        var j = document.getElementById('number').value;
        return Math.pow(j, wert);
    };
</script>
<select id="number" style="margin:40px;">
<option value="1">1=x</option>
<option value="2">2=x</option>
<option value="3">3=x</option>
<option value="4">4=x</option>
</select>
<table border="1mm">
  <tbody><tr><th>x</th><th>2*x</th>
    <script language="javascript">
        for (var i =0; i <= 64; i++) {
        out = "<tr><td>" + i + "</td><td>" + times(i)+ "</td></tr>"
        document.write(out) ;
        } 
    </script>
</body>
هل كانت مفيدة؟

المحلول

The times function is being called once, only as the page writes. Try encapsulating the part that calls the function into the onchange event of the "number" node. I would append the answers to the table rather than document.write them. Try this out:

<head>
<script type="text/javascript">
    function times(wert) {
        var j = document.getElementById('number').value;
        return Math.pow(j, wert);
    };
    function doCalc(){
        document.getElementById("output").innerHTML="<tr><th>x</th><th>2*x</th></tr>";
        for (var i =0; i <= 64; i++) {
            out = "<tr><td>" + i + "</td><td>" + times(i)+ "</td></tr>"
            document.getElementById('output').innerHTML += out;
        }
    }
</script>
<head>
<body>
<select id="number" style="margin:40px;" onchange="doCalc()">
<option value="0">0=x</option>
<option value="1">1=x</option>
<option value="2">2=x</option>
<option value="3">3=x</option>
<option value="4">4=x</option>
</select>
<table border="1mm">
  <tbody id="output">
      <tr><th>x</th><th>2*x</th></tr>
  </tbody>
</table>
</body>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top