如何让用户输入" .pushed"成阵列

时间:2016-02-04 19:01:15

标签: javascript html

我希望用户能够在框中添加一个url提交它,然后它将在数组中并按顺序显示。我希望能够在点击提交时多次发生这种情况。

这就是我的位置,但它在我的计算机上搜索网址而不是网页。

<!DOCTYPE html>
<html>
<head>
<title>images</title>
</head>
<body>
<input type="text" id="user_input" />
<button onClick="add()">ADD</button>
<img id="light" width="10%">
<button onclick="colourChange()">Click Me To Cycle Through The Colours</button> 
<script>
var x=1
var user = document.getElementById("user_input");
var colour = ["red.gif", "amber1.gif", "green.gif", "amber1.gif"];

document.getElementById("light").src = colour[0];
function add(){
colour.push(user);
}

function colourChange(){
    document.getElementById("light").src = colour[x];
    x += 1;
    if (x == colour.length ) x = 0
}
</script>

</body>
</html>

4 个答案:

答案 0 :(得分:0)

如果您希望在用户重新加载页面时重置此项,则无需使用表单。

<input type="text" id="user_input" />
<button onClick=add()>ADD</button>

你的添加功能

function add(){
  var newVal = document.getElementById('user_input').value;
  fruits.push(newVal); //assuming your array is named fruits, I can't see in your code where you have defined it.
}

答案 1 :(得分:0)

替换你的添加功能
var imageInput = document.querySelector("input[name=url]");
function add(evnt){
    evnt.preventDefault();
    colour.push(imageInput.value);
    return false;
}

答案 2 :(得分:0)

首先,您需要在尝试推送之前声明该数组。 var fruits = []; 然后在你的add函数中,获取url元素并推送到之前声明的数组。如果你给元素一个id,这很方便。 function add() { fruits.push(document.getElementById('url').value); }

<!DOCTYPE html>
<html>
  <head>
  <title>images</title>
  </head>
  <body>
    <form id="user">
      insert an image URL to add to cycle: <input type="text" id="url" name="url"><br>
      <button onclick="add()">ADD</button>
    </form>
    <img id="light" width="10%">
    <button onclick="colourChange()">Click Me To Cycle Through The Colours</button>

    <script>
    var x = 1;
    var colour = ["red.gif", "amber1.gif", "green.gif", "amber1.gif"];
    var fruits = [];
    document.getElementById("light").src = colour[0];
    var url = document.getElementById('url');

    function add(){
      fruits.push(url.value);
    }

    function colourChange(){
        document.getElementById("light").src = colour[x];
        x += 1;
        if (x == colour.length ) x = 0
    }
    </script>
  </body>
</html>

答案 3 :(得分:0)

从标记# Eat any remaining input while read -t 1 -n 1 do # Do nothing here : done # Continue processing now that all input has been consumed... 添加,并查看下面一行中提到的onsubmit="return false"函数。

&#13;
&#13;
add()
&#13;
var x=1
var colour = ["red.gif", "amber1.gif", "green.gif", "amber1.gif"];
document.getElementById("light").src = colour[0];
function add(){				
  var newVal = document.getElementById('url').value;
  colour.push(newVal);
  document.getElementById('url').value = '';;
}
function colourChange(){
  document.getElementById("light").src = colour[x];
  x += 1;
  if (x == colour.length ) x = 0
}
&#13;
&#13;
&#13;