在javascript中传递函数的变量

时间:2014-03-14 10:20:19

标签: javascript arrays function variables

我正在尝试将文本作为用户的输入并拆分成数组并传递给它。

<textarea id="texty">
</textarea>
<input type="button" onclick="funky()" />
<script type="text/javascript">
var str;
var array;
var ACL1;
var ACL2;
function funky() {
    str = document.getElementById('texty').value;

    array = str.split(' ');
}
for (var i = 0; i < array.length; i++) {
    var xi = array[i];

    if (xi === "ACL") {
        ACL1 = array[i + 1];
        ACL2 = array[i + 2];
    }
}

我再次使用这段代码在同一页面的其他地方使用变量ACL1和ACL2

 <script type="text/javascript">
 document.write(+ ACL1 + "<br>");
 </script>

 <script type="text/javascript">
 document.write(+ ACL2 + "<br>");
 </script>

有人知道我哪里出错吗?

2 个答案:

答案 0 :(得分:0)

你所有的funky()函数都将字符串拆分成一个数组而已 - 你需要让你的for循环部分变成funky()并看看会发生什么。

答案 1 :(得分:0)

单击按钮时,您可以为array 分配值

您尝试将该数据处理为ACL1ACL2,并在文档加载时将其写入页面。

在文档加载之前单击按钮

  1. for循环移到funky函数
  2. 摆脱document.write脚本。
  3. 用div元素(或其他更符合语义的容器)替换它们。
  4. 修改funky函数,以便在填充变量后将内容添加到页面中
    1. 找到您要将内容放入的元素(例如,使用document.getElementByIddocument.querySelector
    2. 将内容放入其中(例如,使用document.createTextNodedocument.appendChild