【问题标题】:Why it is not printing the character in a paragraph?为什么它不打印段落中的字符?
【发布时间】:2015-08-14 00:40:19
【问题描述】:

编写一个脚本,输入一个字符的整数代码并显示相应的字符。

它应该打印在一个段落中。

function character() {
    var input = document.getElementById( "input" );
    var code = document.getElementById( "output" ).innerHTML = input;
    output.value = String.fromCharCode( code );
}
<input id="input" type="text" size="10">
<br>
<input type="button" value="click here" onclick="character()" id="button">
<br>
<p id="output" ></p>

【问题讨论】:

    标签: javascript


    【解决方案1】:

    这里,这行得通:

    <script>
    function character() {
    var ChrCode = document.getElementById("input").value;
    document.getElementById("output").innerText = ChrCode + " = " + String.fromCharCode(ChrCode);
    //output.value = String.fromCharCode( code );
    }
    </script>
    
    <input id="input" type="text" size="10">
    <br>
    <input type="button" value="click here" onclick="character()" id="button">
    <br>
    <p id="output" >Output</p>
    

    【讨论】:

    • 没问题,@MarkMark
    【解决方案2】:

    P 不是表单元素。另外如果你使用form.fieldName,你需要使用name=""而不是id="";否则对所有字段使用document.getElementById 并忽略该表单。

    段落需要使用 innerHTML 或 innerText/textContent

    document.getElementById("output").innerHTML=...
    

    function character() {
      var form = document.getElementById("form");
      var code = parseInt(form.input.value,10); // radix 10 to make decimal
      document.getElementById("output").innerHTML = String.fromCharCode(code);
    }
    <form id="form">
      <input name="input" type="text" size="10">
      <br>
      <input type="button" value="click here" onclick="character()" id="button">
      <br>
      <p id="output" ></p>
    </form>

    【讨论】:

    • 我必须在 p@mplungjan 中完成
    • 查看包含其他修复的更新 - 我可能为您提供了太多关于家庭作业的信息
    • 那是radix。需要处理输入以 0x 开头的内容的人,其中 x octal
    • 它给了我这个投票需要 15 声望@mplungjan
    • 是的。我的最爱。我阅读了第一版和第二版 JavaScript, the Definitive Guide - 现在是第 6 版。
    【解决方案3】:

    您在访问表单内的元素时遇到问题。

    document.getElementById("form").elements['input']
    

    但这仅适用于表单元素,不适用于其他 HTML 元素。

    在这些元素中,您可以使用 idname 但出于历史原因。

    你有另一种方式:

    function character() {
      var input = document.getElementById("input"),
          output = document.getElementById("output");
          output.innerHTML = String.fromCharCode(parseInt(input.value), 10) || '';
    }
    <form id="form">
      <input id="input" type="text" size="10">
      <br>
      <input type="button" value="click here" onclick="character()" id="button">
      <br>
      <p id="output" ></p>
    </form>

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 2012-09-13
      • 2015-08-26
      • 2017-09-09
      相关资源
      最近更新 更多