【问题标题】:how to properly loop through form elements in javascript如何在javascript中正确循环表单元素
【发布时间】:2010-11-21 02:29:43
【问题描述】:

我要做的是从每个表单元素中获取“文本”类型的值。你能教我从文本框中获取值并使用 javascript 输出这些值的正确方法吗?

<head>
<script type="text/javascript">
function trap(){
for(var i=0; i<document.x.elements.length; i++)
{
document.write(document.x.elements[i].value + "<br />");
}
}
</script>
</head>
<body>


<form name="x">

<?php
for($i=0;$i<2;$i++){
?>

qty #<?php echo $i; ?>
<input type="text" name="qty[<?php echo $i; ?>]" value=""/>
<img src="add-icon.png" onmouseover="trap();">

<?php } ?>

</form>

</body>

我检查了它是否获得了正确数量的文本类型的表单元素:

document.write(document.x.elements.length);

它与我在 php for 循环中指定的数字相同。但是我只得到元素 #1 的值。它似乎没有从 qty[1] 获取值

请帮忙。谢谢

【问题讨论】:

    标签: javascript arrays forms


    【解决方案1】:

    你的问题是另一个:

    您在函数中使用document.write()。此方法在页面加载后无法使用,因为它会覆盖整个文档-> 也会覆盖函数本身。这样,在第一次调用 write 后,该函数不再存在,您将获得一个仅包含您刚刚写入的数据的新文档。

    使用其他方法代替 write(),例如这应该可以工作:

    document.body.appendChild(document.createTextNode(document.x.elements[i].value ));
    document.body.appendChild(document.createElement('br'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2019-04-03
      相关资源
      最近更新 更多