为什么我的 JavaScript RGB Hex 转换器不工作?

Why is my JavaScript RGB Hex converter not working?

我在 JavaScript 中制作了一个 RGB 十六进制转换器。但是我的代码不起作用。

我的问题:“首先,我在 hextxt 输入中键入了一个十六进制。然后,我按下 Hex to RGB 按钮将我的十六进制转换为 rgb。但它不起作用。”

这是我的代码:

function rgb_to_hex() {
    var r = +rtxt.value;
    var g = +gtxt.value;
    var b = +btxt.value;
    var rhex1 = r.toString(16);
    var ghex1 = g.toString(16);
    var bhex1 = b.toString(16);
    var hex1 = "Hex: #" + rhex1 + ghex1 + bhex1;
    p.innerHTML = hex1;
}

function hex_to_rgb() {
    var hex2 = +hextxt.value;
    var rhex2 = hex2.charAt(0) + hex2.charAt(1);
    var ghex2 = hex2.charAt(2) + hex2.charAt(3);
    var bhex2 = hex2.charAt(4) + hex2.charAt(5);
    var rgb = "RGB: " + rhex2 + ", " + ghex2 + ", " + bhex2;
    p.innerHTML = rgb;
}
<input type="text" id="rtxt" />
<br>
<input type="text" id="gtxt" />
<br>
<input type="text" id="btxt" />
<br>
<input type="text" id="hextxt" />
<br>
<button onclick="rgb_to_hex()">RGB to Hex</button>
<br>
<button onclick="hex_to_rgb()">Hex to RGB</button>
<p id="p"></p>

  function rgb_to_hex() {
    var r = +rtxt.value;
    var g = +gtxt.value;
    var b = +btxt.value;
    var rhex1 = r.toString(16);
    var ghex1 = g.toString(16);
    var bhex1 = b.toString(16);
    var hex1 = "#" + rhex1 + ghex1 + bhex1;
    document.getElementById("hextxt").value = hex1;
}

function hex_to_rgb() {
    var hex2 = hextxt.value;
    var rhex2 = hex2.charAt(1) + hex2.charAt(2);
    var ghex2 = hex2.charAt(3) + hex2.charAt(4);
    var bhex2 = hex2.charAt(5) + hex2.charAt(6);

    document.getElementById("rtxt").value=parseInt(rhex2,16);
    document.getElementById("gtxt").value=parseInt(ghex2,16);
    document.getElementById("btxt").value=parseInt(bhex2,16);

}
<input type="text" id="rtxt" />
<br>
<input type="text" id="gtxt" />
<br>
<input type="text" id="btxt" />
<br>
<input type="text" id="hextxt" />
<br>
<button onclick="rgb_to_hex()">RGB to Hex</button>
<br>
<button onclick="hex_to_rgb()">Hex to RGB</button>

+hextxt.value 代码不正确。正确的代码是 hextxt.value.