Javascript将输入文本移动到另一个标记中

时间:2016-05-19 18:47:03

标签: javascript html input

我正在尝试获取值,字母,并将该值移动到文档中的其他位置。因此,如果在文本框中输入“t”,我想将输入的值移到上面的<p>标记中吗?我不确定如何更具描述性,所以我在下面提供了我的html和javascript代码。

仅供参考我在编程训练营中我们使用纯Javascript进行此任务而不是JQuery,我也是全新的,所以请原谅我这是一个愚蠢的问题。这是我到目前为止所拥有的

`

<!DOCTYPE html>
<html>
<body>

    <h1>The Psychic Game</h1>
    <h2>Guess what letter I'm thinking of.</h2>
    <h3 id="wins">Wins:</h3>
    <h3 id="losses">Losses:</h3>
    <h3 id="guess">Guess Left:</h3>
    <h3 id="guess_num">Your Guesses so Far: <p id="guess_val"> </p></h3>
    <form>
        <input type="text" name="guess_letter" value="">
    </form>
</body>

</html>`

`var guessLetter = document.getElementById("guess_letter");

    function letterPick(guessLetter){

    }

`

1 个答案:

答案 0 :(得分:1)

我在这里做的是保存我们将用于变量的两个元素。然后我将keyup事件监听器添加到输入字段。每次按下一个键,我们都想更改p标签的innerHTML

<!DOCTYPE html>
<html>
<body>

    <h1>The Psychic Game</h1>
    <h2>Guess what letter I'm thinking of.</h2>
    <h3 id="wins">Wins:</h3>
    <h3 id="losses">Losses:</h3>
    <h3 id="guess">Guess Left:</h3>
    <h3 id="guess_num">Your Guesses so Far: <p id="guess_val"> </p></h3>
    <form>
        <input type="text" name="guess_letter" value="">
    </form>
    <script>
        var input = document.querySelector('[name="guess_letter"]');
        var p = document.getElementById('guess_val');

        input.addEventListener('keyup', (e) => {
          p.innerHTML = e.currentTarget.value;
        });
    </script>
</body>
</html>

&#13;
&#13;
var input = document.querySelector('[name="guess_letter"]');
var p = document.getElementById('guess_val');

input.addEventListener('keyup', (e) => {
  p.innerHTML = e.currentTarget.value;
});
&#13;
<!DOCTYPE html>
<html>
<body>

    <h1>The Psychic Game</h1>
    <h2>Guess what letter I'm thinking of.</h2>
    <h3 id="wins">Wins:</h3>
    <h3 id="losses">Losses:</h3>
    <h3 id="guess">Guess Left:</h3>
    <h3 id="guess_num">Your Guesses so Far: <p id="guess_val"> </p></h3>
    <form>
        <input type="text" name="guess_letter" value="">
    </form>

</body>

</html>
&#13;
&#13;
&#13;