javascript - 如何使用 Javascript 将数组从 textarea 移动到表格
问题描述
我正在尝试将输入结果从 textarea 移动到表格中。我正在使用 javascript 来获取数组值。
但我现在能做的只是在一个文本区域中显示它。我很困惑如何将数组值分隔到表中。
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
<input type="button" value="next" onclick="next3();">
<textarea id="koord" value="" style="width:220px;"></textarea>
<script>
function next3(){
var vx = String($("input[name='px[]']").map(function(){return $(this).val();}).get());
var vy = String($("input[name='py[]']").map(function(){return $(this).val();}).get());
var vxArr = vx.split(",");
var vyArr = vy.split(",");
var lenArr = vxArr.length;
var isi = "";
for (i = 0; i < lenArr; i++) {
var koord = "X" + vxArr[i] + " " + "Y" + vyArr[i];
//alert (koord);
var isi = isi + ', ' + koord;
}
//alert (isi);
var lastChar = isi.substr(2); // => "1"
$("#koord").val(lastChar);
}
</script>
textarea 中的结果是
图片链接https://postimg.cc/fJWHhxp9
我所期望的是
+---------+---------+
| X Point | Y Point |
+---------+---------+
| 123 | 456 |
| 123 | 456 |
| 123 | 456 |
| 123 | 456 |
+---------+---------+
解决方案
您有固定长度的输入,您可以轻松地将数组用作值并从中生成表,而不是字符串,您可以将其保留为数组并附加行。
function next3() {
var vx = ($("input[name='px[]']").map(function() {
return $(this).val();
}).get());
var vy = ($("input[name='py[]']").map(function() {
return $(this).val();
}).get());
$('table tbody').html('');
vx.forEach((a, index) => {
if (a !== '' && vy[index] !== '') {
$('table tbody').append('<tr><td>' + a + '</td><td>' + vy[index] + '</td></tr>')
}
})
}
table {
border: 1px solid black
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br> x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br> x <input type="text" name="px[]" value="" /> y <input type="text"
name="py[]" value="" /><br> x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
<input type="button" value="next" onclick="next3();">
<textarea id="koord" value="" style="width:220px;"></textarea>
<table>
<thead></thead>
<tbody></tbody>
</table>
推荐阅读
- python - 在网络刮板脚本的 for 循环中仅反转没有数字的字符串
- php - 带有ajax的php-mysql登录系统
- amazon-web-services - 如何将新容器附加到 AWS ECS 中正在运行的任务?
- r - 如何使用插入符号(maxit)为地球传递 glm 控制参数
- ruby-on-rails - Rails API 在 camelCase 中呈现所有响应
- c - C中的Pthread_cond_wait
- reactjs - Typescript 访问嵌套在其他类型中的对象
- java - mac 中的“java_home”实用程序无法找到新安装的 amazon corretto 11 JDK
- javascript - 我有一个基于所选城市长度不同的对象数组。如何选择包含具有特定属性的对象的元素?
- mongodb - Ubuntu软件无法安装程序