我有一个想法,可以在单击按钮时动态创建单个数组值 这是我在本地运行的代码,
function clearr()
{
var exp ='25';
let btn = document.getElementById("clear");
let val = btn.value;
var d=0;
for($i=0; $i<=3;$i++){
if(val=='C')
{
if(d==1){
d=d;
}else if(d===undefined){
d=0;
// alert(d);
// return false;
}else{
d=d;
}
const Vio=[];
Vio.push(exp);
console.log(Vio);
d++;
}
}
}
我 think 我明白你想要什么,看起来你想多了。要将按钮附加到数组,需要在全局范围内定义数组,而不是函数的局部范围,就像您拥有的那样。此外,列表不能是
const
,因为这意味着您无法修改它。
对于这个简单的案例,您不需要任何
if
条件。您的函数需要做的就是检索按钮的当前值并将该值推送到数组中。
我会拿出一个片段来演示。为此,输入将来自文本字段而不是按钮。单击“添加”将调用
add
函数,该函数将文本字段的值附加到数组 some_list
上。单击“打印”会将列表的内容打印到控制台。
var some_list = []
function add() {
// Get a handle to the text field
var element = document.getElementById("textfield")
// Add the current text field's value to an array
some_list.push(element.value)
}
<input id ="textfield" type = "text"></input>
<!-- This button will cause the value in the above text field to be added to a running list-->
<button onclick="add()">Add</button>
<br><br>
<!-- Print out the array-->
<button onclick="console.log(some_list)">Print</button>