如何将字符串转换为来自按钮输入的Int

时间:2014-11-26 08:55:19

标签: javascript html string int

我需要转换来自我的innerHTML的字符串,这是通过点击按钮接收的(我正在制作一个计算器) 如果需要,这是我的JS:

window.onload = function () {
// your code here
var counter = document.getElementById("scherm");
    var optellen = document.getElementById("1");
    var buttons = document.getElementsByTagName("button");
    var operators = ["+", "-", "*", "/", "=", "C"]

    // maak for loop voor buttons 
    for(var i=0; i<buttons.length; i++)
    {
        buttons[i].addEventListener("click", screen);
    }

    //optellen.addEventListener("click", screen); //+ string + sting aan het einde als je wilt gaan uitrekenen doe je parseInt()

    function screen() {
        if( operators.indexOf(this.innerHTML) != -1)
        {   

            if( operators.indexOf(this.innerHTML) == 5)
            {
                document.getElementById("scherm").innerHTML="";
            }

        }
        else
        {

            counter.innerHTML += this.innerHTML;
        }

        console.log(this.innerHTML);

        //if(counter.innerHTML == this.inner)
        //counter.innerHTML = buttons.innerHTML;
        //
    }

};

按要求提供的HTML: <div id="rekenmachine"> <header><p id="scherm"></p></header> <section id="knoppen"> <div class="row"> <button value="1">1</button> <button value="2" class="pos">2</button> <button value="3" class="pos">3</button> <button value="+" class="pos">+</button> </div> <div class="row"> <button value="">4</button> <button value="" class="pos">5</button> <button value="" class="pos">6</button> <button value="" class="pos">-</button> </div> <div class="row"> <button value="">7</button> <button class="pos">8</button> <button class="pos">9</button> <button class="pos">*</button> </div> <div class="row"> <button value="">C</button> <button value="" class="pos">0</button> <button value="" class="pos">=</button> <button value="" class="pos">/</button> </div> </section>

3 个答案:

答案 0 :(得分:0)

这应该这样做。

parseInt("10");

来源:http://www.w3schools.com/jsref/jsref_parseint.asp

答案 1 :(得分:0)

看看这个:

http://www.w3schools.com/jsref/jsref_parseint.asp

(你应该这样做:parseInt(counter.innerHTML))

 else {
     var result;
     if(counter.innerHTML != "") { 
         result = parseInt(counter.innerHTML);
      } else {
          result = 0;
      } 
     result += parseInt(this.innerHTML); 
     counter.innerHTML = result; }

答案 2 :(得分:0)

你可以尝试

解析功能。如果击中一个字符而不是识别,则解析将停止。如果解析在第一个符号处停止,则返回NaN

parseInt("1") = 1
parseInt("1a") = 1
parseInt("a1") = NaN

更改类型。

一元加号

+"1" = 1
+"1.231" = 1.231
+"1a" = NaN
+"a1" = NaN

按位NOT

~~"1" = 1
~~"1.231" = 1
~~"a1" = 0
~~"1a" = 0
~~"a" = 0

乘法运算符

"1" * 1 = 1
"1a" * 1 = NaN
"a1" * 1 = NaN
"a" * 1 = NaN