我有一个 html/css 页面,应该使用充满按钮的 html 表格布局来模拟 t9 键盘布局。
在页面上,我有一个包含两个文本字段的表单。我想使用表格/键盘值通过 JavaScript 来填充文本字段中的数字。
我能够将一个变量与一个字符串关联起来,该字符串描述了我希望用数据填充哪个字段,但是当我调用该字段的当前值时,我收到一个错误(console.log),上面写着“cannot读取“未定义”的属性“x”。
这是我的函数。
function place(id) {
var key = ""; //Ensure that this is a string, not number
key = document.getElementById(id).id; //Get the key value.
console.log(key);
var total = ""; //initialize variable.
console.log(appSettings.padName);
total = nums.element[appSettings.padName].value; //Grab total.
//if (total.contains("Click")) total = "";
console.log(total);
if (key == "-1") total.slice(0, -1); //backspace.
else if (key == "-2") numPad(appSettings.padName); //Enter.
else total += key; //concat to end of the String.
document.getElementById(appSettings.padName).value += total; //place update.
}
我使用以下 html 调用此函数
<div id="nums">
<form name="nums">
<h3>
Cell number: <input type="text" id="cell" value="" class="inputText" size="10" onclick="numPad('cell')" name="cell" /><br/><br/>
<div id='group'>
Party size: <input type="text" value="" class="inputText" size="10" onclick="numPad('group')" name="group" /><br/><br/>
</div>
<input type="submit" value="Submit" class="button" />
</h3>
*请注意,每个字段都有不同的 ID 系统。
收集变量的函数工作正常,以字符串格式(也称为“单元格”)收集 div ID。如果您需要更多信息来帮助我,我很乐意提供:P
最佳答案
我会采用完全不同的方法来解决这个问题。最好的解决方案是监听 click
事件于 <table>
,从那里您可以获取已单击的键,并相应地更新其中一个输入。这种做法称为事件委托(delegate),而且非常高效。
您当前的 JavaScript 有一些错误。首先,在为变量分配您想要的值之前,您不需要初始化变量并为其分配“类型”。同样,您不需要通过 ID 来查找元素,只是为了再次获取 ID,这是浪费的。我注意到您还在函数中引用了许多全局变量,这通常是不好的做法。
另一个说明,克里斯·莱弗利(Chris Lively)向您提供的信息,关于:分号是公然错误的。您原来的 if 语句没有问题。您可以从这篇文章中了解更多信息:http://inimino.org/~inimino/blog/javascript_semicolons
关于javascript - 连接表格数据和表单文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7005436/