javascript
  • html
  • button
  • onclick
  • 2013-06-28 146 views 0 likes 
    0

    好的。我做了一个计算2的权力的程序。我有html代码。但我首先为你描述它。有一个输入id ='inputin',下面有一个按钮。在输入你写一个数字。这个数字将是两个指数,你按下按钮后,结果会出现一个窗口的console.loghtml按钮和javascript代码

    这里的HTML:

    <div id='main'> 
        <input type="number" name="power2" placeholder='Enter the power' id='inputin'><br/> 
        <button id="submit" onclick="binaryS()">Do it!</button> 
    
        </div> 
    

    和JavaScript:

    binaryS = function() { 
    x = document.getElementById("inputin").value; 
    y=1; 
    for(i=1;i<=x;i++) { 
        y=y*2; 
    } 
    console.log (y); 
    }; 
    

    为什么它不起作用?任何帮助?如果你可以建议,而不是一个丑陋的console.log窗口我怎么能出现在一个新的div在页面的某个地方?日Thnx

    +0

    我会用'警报(Y)'对于快速检查(没什么奇怪的) –

    +0

    Y = 1时每次都不会得到相同的答案吗? – Learner

    +0

    它适合我。 http://jsfiddle.net/barmar/a9FrL/ – Barmar

    回答

    7

    你的JavaScript应该是:

    function binaryS() { 
        var x = document.getElementById("inputin").value; 
        document.getElementById("outputValue").innerHTML = Math.pow(2,x); 
    } 
    

    放置你的页面显示的某处以下:

    <div id="outputValue">Result</div> 
    
    +0

    不错的表演老伙计! – abc123

    +0

    +1当我建立[这个小提琴](http://jsfiddle.net/GolezTrol/rcVrV/2/)的时候,我会打败它,它本质上是一样的,只有'span'和'innerText'。而不使用'数学'。 :p – GolezTrol

    +0

    这是我第一次真正的答案:D感谢这个可爱的网站,我很少有问题要问! –

    1

    试试这个功能:

    function nearestPow2(){ 
        return Math.pow(2, Math.round(Math.log(document.getElementById("inputin").value;)/Math.log(2))); 
    } 
    

    编号:http://weblog.bocoup.com/find-the-closest-power-of-2-with-javascript/

    0

    没有深入细节,您的代码正在工作。我做了一个HTML页面来证明它:

    <html> 
        <head> 
         <script type="application/x-javascript"> 
          binaryS = function() { 
           x = document.getElementById("inputin").value; 
           y=1; 
           for(i=1;i<=x;i++) { 
            y=y*2; 
           } 
           document.getElementById('result').innerHTML = y 
          }; 
         </script> 
        </head> 
        <body> 
         <div id='main'> 
          <input type="number" name="power2" placeholder='Enter the power' id='inputin'><br/> 
          <button id="submit" onclick="binaryS()">Do it!</button> 
         </div> 
         <div id="result" ></div> 
        </body> 
    </html> 
    

    我也用的,而不是一个自定义的数学运算Math.pow建议你:

    Math.pow(2, parseInt(document.getElementById("inputin").value)); 
    
    相关问题