<html>
<body>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<table>
<tr>
<td><input type = 'button' value = "key[0][1]" /></td>;
</tr>
</table>
</body>
</html>
这是上面的一个小例子,但我基本上是在制作一个屏幕键盘,我已经有了定位按钮的循环,但是在我的循环中我尝试分配每个键的值,类似于上面的代码,但是而不是为每个键打印qwerty,它为每个按钮打印键[row] [col]。如何使用与上述相似的方法将字母显示在按钮上?
答案 0 :(得分:3)
以下代码生成您期望的键盘类布局:
<html>
<head>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<body>
<script type="text/javascript">
for(var i = 0; i < key.length; i++)
{
document.write("<div>");
for(var j = 0; j < key[i].length; j++)
{
document.write("<input type='button' value='" + key[i][j] + "'/>");
}
document.write("</div>");
}
</script>
</body>
</html>
第二排和第三排应该向右移动一点看起来像真正的键盘。为此我们可以为div标签做填充。希望这会对你有所帮助。
答案 1 :(得分:1)
这样的东西?
HTML:
<input id="myInput" type="button" />
JavaScript的:
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var input = document.getElementById('myInput');
input.value = key[0][1];
这是基本的想法。你已经有了一个循环可以使用。在页面上的HTML之后,javascript应该是。在获取它们之前,您的元素需要存在。但不确定这是否是您的确切混淆。
您可以使用javascript创建元素,但除非有理由这样做,否则您也可以编写HTML。如果您使用javascript函数生成元素并填充其值,则需要javascript document.createElement
:
var keysArr = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var generateKeys = function(keys) {
for (var i = 0 ; i < keys.length ; i++) {
for (var j = 0 ; j < keys[i].length ; j++) {
var input = document.createElement('input');
input.value = key[i][j];
document.appendChild(input); // or put it wherever you need to.
}
}
}
generateKeys(keysArr);
如果你想让用户动态选择不同的布局,那么将它包装在一个函数中也可以让你重复使用不同键盘布局的代码。
答案 2 :(得分:0)
您需要以编程方式设置它们,而不是在value属性中设置它们。
您还需要以编程方式在循环中创建tr / td / input元素,例如:
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
以编程方式创建输入标记时,可以使用javascript设置value属性 - 例如。
newInput.setAttribute("value", key[rowIndex, cellindex]);