简体   繁体   English

纯Javascript-将文本输入的值添加到 <li> 单击按钮/输入键时

[英]Pure Javascript - Add the value of text input to <li> when button clicked/enter-key

I'm a very new user of Javascript and I'm having trouble with getting the value of a user's input when you click the button or hit enter. 我是Javascript的新手,单击按钮或按Enter时,无法获取用户输入的值。 Here is what I have so far, it does indeed add things to the li but it doesn't accept the value. 到目前为止,这是我所拥有的,确实确实在li中添加了一些东西,但它不接受该值。

I'd like this to all be in pure JS (not jQuery). 我希望所有这些都使用纯JS(而不是jQuery)。

Here is my HTML 这是我的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 />

And my JS 还有我的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);
  }

Here is a demo https://jsfiddle.net/sthig/hhuw0rtr/ 这是一个演示https://jsfiddle.net/sthig/hhuw0rtr/

Thanks for you help and listening to me get my head around the js verbiage correctly! 感谢您的帮助,并听我说正确地理解了js语言!

This isn't really an issue with "binding"--there's no such concept in vanilla JS. 对于“绑定”来说,这实际上不是问题-在香草JS中没有这样的概念。

Instead you need to make sure that you're grabbing the value of the text field when the onclick handler is called: 相反,您需要确保在调用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);
  }

You can also reduce this to: 您还可以将其减少为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM