从Javascript / HTML中的动态创建按钮读取值

时间:2016-12-12 15:29:56

标签: javascript html

我创建了一个虚拟键盘,并尝试使用按钮上显示的字母填充输入框。我有以下功能:

此函数接受一个字符并创建一个以char为其值的按钮:

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerText = char; //fill it with char
  btn.id = "btn";
  keyStroke()
  return btn;
}

此功能为所有字母创建一个按钮:

var keyList = "QWERTYUIOPASDFGHJKLZXCVBNM";
for (i in keyList)
{
  var button = keyButton(keyList[i]);
  document.body.appendChild(button)
}

此功能是问题,它应该从按钮读取值并将其附加到输入框:

function keyStroke() {
  document.getElementById("searchBar").value += document.getElementById("btn").innerText;
}

输入框的HTML如下所示:

<input id="searchBar" class="inputBar" placeholder="Enter something" />

3 个答案:

答案 0 :(得分:3)

试试这个:

&#13;
&#13;
var keyList = "QWERTYUIOPASDFGHJKLZXCVBNM";

for (var i in keyList) {    //loop through letters in keyList
  var button = keyButton(keyList[i]);
  document.body.appendChild(button);
}

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerHTML = char; //fill it with char
  btn.onclick = function () { keyStroke(this); };
  return btn;
}

function keyStroke(b) {
  document.getElementById("searchBar").value += b.innerHTML;
}
&#13;
<input id="searchBar" class="inputBar" placeholder="Enter something" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您为创建它的按钮单击事件创建事件处理程序,则可以在单击按钮时获取按钮的数据

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerText = char; //fill it with char
  btn.id = "btn";
  btn.onclick = function() {//yourcodehere}
  keyStroke()
  return btn;
}

或者您仍然可以使用您创建的功能

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerText = char; //fill it with char
  btn.id = "btn";
  btn.onclick = keyStroke;
  keyStroke()
  return btn;
}

但是这样你需要稍微更改keyStroke功能,以获取事件的来源。

function keyStroke(evt) {
  document.getElementById("searchBar").value += evt.target.innerText;
}

答案 2 :(得分:0)

找到以下工作解决方案:

添加带标签的按钮

function keyButton(chara) {
var btn = document.createElement("button"); //create button
btn.innerText = chara; //fill it with char
btn.id = "btn";
btn.onclick=onclickFunction;
return btn;
}

点击按钮功能:

function onclickFunction(ev){
var searchBar=document.getElementById('searchBar');
searchBar.value=searchBar.value + ev.srcElement.innerText;
}