gpt4 book ai didi

javascript - 纯 Javascript - 单击按钮/输入键时将文本输入的值添加到
  • 转载 作者:行者123 更新时间:2023-12-01 03:54:53 26 4
    gpt4 key购买 nike

    我是 Javascript 的新用户,当您单击按钮或按 Enter 键时,我无法获取用户输入的值。这是我到目前为止所拥有的,它确实向 li 添加了一些东西,但它不接受该值。

    我希望这一切都在纯 JS(而不是 jQuery)中。

    这是我的 HTML

      <h2>I'd like to bind here</h2>


    <input type="text" class="theplayer" name="Player" id="bind" value="Player-name" />
    <input type="button" id="thego" value="Go" /><br />

    还有我的 JS

    const el = document.getElementById('bind');
    const gobutton = document.getElementById('thego')
    let nameOfPlayer = el.value;
    gobutton[window.addEventListener ? 'addEventListener' : 'attachEvent']( window.addEventListener ? 'click' : 'onclick', myClickFunc, false);
    function myClickFunc()
    {
    var x = document.createElement("LI");
    var t = document.createTextNode(nameOfPlayer);
    x.appendChild(t);
    document.getElementById("teammateys").appendChild(x);
    }

    这是一个演示 https://jsfiddle.net/sthig/hhuw0rtr/

    感谢您的帮助并听我正确理解 js 术语!

    最佳答案

    这实际上并不是“绑定(bind)”的问题——原生 JS 中没有这样的概念。

    相反,您需要确保在调用 onclick 处理程序时获取文本字段的值:

    function myClickFunc()
    {
    var currentValue = document.getElementById("bind").value;
    var x = document.createElement("LI");
    var t = document.createTextNode(currentValue);
    x.appendChild(t);
    document.getElementById("teammateys").appendChild(x);
    }

    您还可以将其减少为:

    function myClickFunc()
    {
    var x = document.createElement("li");
    x.textContent = document.getElementById("bind").value;
    document.getElementById("teammateys").appendChild(x);
    }

    关于javascript - 纯 Javascript - 单击按钮/输入键时将文本输入的值添加到 <li>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42846637/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com