首先,我應該說我是一個javascript新手,所以原諒我的無知。 我創建了一個具有三個功能並且使用數組的表單: Add - 要接受一個名稱(如果字段留空,它應該要求用戶在警告框中輸入一個名稱) 查找 - 驗證名稱是否有尚未輸入(在警告框中) 列表 - 列出已輸入的名稱(在警告框中)JavaScript提醒用戶已經輸入相同的信息
我有列表功能工作(良好)。輸入名稱後出現提示輸入名稱,以及當您將字段留空(不好) ,我無法使查找功能正常工作。 我的代碼在下面,我試了很多次迭代,並搜索了這麼多的網站尋求幫助,也嘗試過螢火蟲;我希望有人能指出我正確的方向。 無題
<body>
<script type="text/javascript">
var a = new Array();
function list() {
var s = "";
for (i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add() {
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
if (myTextField.value == "") {
alert("Please enter a name");
return false;
}
function find() {
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField) {
alert("Sorry, the name " + a[i] + " already exists. Try again");
}
}
}
</script>
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="list()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
</body>
</html>
謝謝你了,我看到我錯在哪裏。它現在完美地工作! – user2948381
np :)很高興可以幫助你。 – Swati