在javascript中从十进制转换为八进制,二进制和十六进制

我有一个表单,用户输入一个十进制数,然后从他选择的下拉菜单中选择是否要通过单击转换按钮将其转换为二进制,八进制或十六进制.新答案应以新形式显示,例如:“二进制数字是……”.但是,我所做的代码似乎不起作用.任何帮助将受到高度赞赏.这是我到目前为止的代码:

   <html>
    <head>
        <title> Convertor </title>


<style>

  .panel {
    width:400px;
    height:160px;
    background-color: #E6E6FA;
    border:2px solid blue;  
    font-weight: bold;
    font-size: 110%;   
    margin-left:30px;
    margin-top:15px; 
   }    

   p {
    margin-left: 30px;
    margin-top: 15px;
   }

   form {
    margin-left: 30px;
    margin-top: 15px;
   }

   button {
    margin-left:40px;
    margin-top:10px;
   }


   .answer {
    width:400px;
    height:90px;
    background-color: #E6E6FA;
    border:2px solid blue;  
    font-weight: bold;
    font-size: 110%;   
    margin-left:30px;
    margin-top:15px; 
   }    

   form {
    margin-left: 70px;
    margin-top: 65px;
   }


</style>


</head>
<body>
    <div class="panel">

        <p>
            Enter decimal number to convert, select Base and click CONVERT.
        </p>

        <form>
            <input type="text">


        <select id="selectid" name="selectname">
            <option value="binary">Binary</option>
            <option value="octal">Octal</option>
            <option value="hexadecimal">Hexadecimal</option>
        </select>   

        <button id="button1" name="Button1" onclick="Answer()"> Convert 
            </button>   

            </form>


    </div>

    <div class="answer">
        <form>


        </form>

    </div>

    <script>


    function Answer() {

        if (document.getElementbyId ('selectid').value=="binary") {
            this.value=this.value.toString(2);
        }
        else if  (document.getElementbyId ('selectid').value=="octal") {
            this.value=this.value.toString(8);
        }
        else if  (document.getElementbyId ('selectid').value=="hexadecimal") {
            this.value=this.value.ToString(16);
        }
    }

    </script>

</body>
最佳答案
十进制到十六进制/八位/二进制:

var hex = (100).toString(16);     // "64"
var oct = (100).toString(8);      // "144"
var bin = (100).toString(2);      // "1100100"

并向后相同:

var dec = parseInt("64",16);      // 100
var dec = parseInt("144",8);      // 100
var dec = parseInt("1100100",2);  // 100

转载注明原文:在javascript中从十进制转换为八进制,二进制和十六进制 - 代码日志