有了这段代码,我们可以向搜索字段发送一个值。现在,考虑到这个例子,我们如何用同一个按钮依次插入更多的值,例如:值1,值2,值3...?
<form id="form1" name="form1" method="post">
<p>
<input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
<script type="text/javascript">
function setValue() {
document.getElementById('bbb').value = "valor 1";
}
</script>
你只要做一个计数器就可以了。
var valor = 0;
function setValue() {
valor++;
document.getElementById('bbb').value = "valor " + valor;
}
<form id="form1" name="form1" method="post">
<p>
<input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
这是两种解决方案,一种是随机插入值,另一种是按顺序插入。它们都能完美地工作。
<form id="form1" name="form1" method="post">
<p>
<input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
<script type="text/javascript">
const myValues = ['Decoration', 'Health', 'Fun', 'Yesterday 4'];
function setValue() {
const randomNum = Math.floor(Math.random() * myValues.length); ;
document.getElementById('bbb').value = myValues[randomNum];
}
</script
<form id="form1" name="form1" method="post">
<p>
<input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
<script type="text/javascript">
const myValues = ['Decoration', 'Health', 'Fun', 'Yesterday 4'];
let myInd = 0;
function setValue() {
document.getElementById('bbb').value = myValues[myInd];
myInd = myInd >= (myValues.length - 1) ? 0 : myInd+1;
}
</script>