所以现在我得到了一个''每次我在输入字段上按提交后链接到myFunction函数的分隔符。我想删除','分隔符。因为当我现在提交一个名字时,它只会打印一个逗号并在每次按下提交时添加另一个逗号而不填写输入字段。
var namenOSM = [];
var clubOSM = ["Wolves", "Derby", "Cardiff", "Aston villa", "Bristol City", "Sheffield utd", "Fulham", "Middlesbrough", "Brentford", "Leeds", "Preston", "Ibswich", "Norwich", "Nottingham", "Millwall", "QPR", "Sheffield Wed", "Redding", "Barnsley", "Bolton", "Hull city", "Sunderland", "Birmingham", "Burton"];
function myFunction() {
var newArray = document.getElementById("naam").value;
document.getElementById("naam").value = "";
namenOSM.push(newArray);
var clubRandom = Math.floor(Math.random() * clubOSM.length);
var node = document.createElement("LI");
var textnode = document.createTextNode(namenOSM + ' = ' + clubOSM[clubRandom]);
node.appendChild(textnode);
document.getElementById("namen").appendChild(node);
}

Player:<br>
<input id="naam" type="text" name="firstname" value="">
<br>
<br>
<input type="button" value="Submit" onclick="myFunction()">
<div id="namen">
</div>
&#13;
我知道俱乐部已硬编码到阵列中,但这对我来说是一个快速学习javascript的项目。
谢谢!
答案 0 :(得分:0)
问题是您输出的是整个数组而不是最后一个索引。
var textnode = document.createTextNode(namenOSM + ' = ' + clubOSM[clubRandom]);
应该是
var textnode = document.createTextNode(namenOSM[namenOSM.length-1] + ' = ' + clubOSM[clubRandom]);
或
var textnode = document.createTextNode(newArray + ' = ' + clubOSM[clubRandom]);
答案 1 :(得分:0)
您应该为firstname
输入应用空输入控件,并注意名称方便,newArray
不是数组。
var namenOSM = [];
var clubOSM = ["Wolves", "Derby", "Cardiff", "Aston villa", "Bristol City", "Sheffield utd", "Fulham", "Middlesbrough", "Brentford", "Leeds", "Preston", "Ibswich", "Norwich", "Nottingham", "Millwall", "QPR", "Sheffield Wed", "Redding", "Barnsley", "Bolton", "Hull city", "Sunderland", "Birmingham", "Burton"];
function myFunction() {
var textValue = document.getElementById("naam").value;
if(textValue == "")
return;
document.getElementById("naam").value = "";
namenOSM.push(textValue);
var clubRandom = Math.floor(Math.random() * clubOSM.length);
var node = document.createElement("LI");
var textnode = document.createTextNode(namenOSM + ' = ' + clubOSM[clubRandom]);
node.appendChild(textnode);
document.getElementById("namen").appendChild(node);
}
&#13;
Player:<br>
<input id="naam" type="text" name="firstname" value="">
<br>
<br>
<input type="button" value="Submit" onclick="myFunction()">
<div id="namen">
</div>
&#13;
答案 2 :(得分:-1)
这是如果你想保持输出完全相同,只是没有逗号,否则看看@epascarello回答
之所以这样,是因为你打印出的是对象数组而不是数组的单个元素。要做到这一点,你需要一个for循环
https://www.w3schools.com/js/js_loop_for.asp
我添加了它,因此它将数组中的所有元素添加到字符串中,然后显示该字符串。
for(var i = 0; i < namenOSM.length; i++){
teamString += namenOSM[i] + " ";
}