我正在跟进我之前提出的问题 here
我已经编写了我的代码,并且根据该帖子的答案,我已经消除了该错误。现在,我没有从选择菜单中的数组中获得任何输出到控制台或结果,之前,当我在不使用 jQuery 的情况下编写此练习时,我能够有效地将项目放入数组中并将其显示在我的选择菜单中。为了获得更完整的答案,我发布了完整的 html 和 javascript/jquery 代码。如果有人对我的代码不起作用的原因有任何意见,我将不胜感激。我的目标是使用 jQuery(我现在正在学习的)来实现我之前单独使用 javascript 所做的事情。在本练习中,我使用用户输入字段,供用户通过单击按钮将客户端添加到阵列中。按下该按钮后,我希望我的脚本检查数组以查看它是否包含该项目,如果不包含,则将元素插入数组并将其显示在现有客户端的选择列表中。
<!DOCTYPE html>
<html>
<head>
<title>Keeper of Time</title>
<link rel="stylesheet" type="text/css" href="kot.css">
<script type ="text/javascript" src="http://code.jQuery.com/jquery-latest.min.js"></script>
</head>
<body>
<div class="navDiv">
<ul id="navButtons">
<li><a href="">Home</a></li>
<li><a href="">Clients</a></li>
<li><a href="">Entries</a></li>
<span><li><a href="">Account</a></li></span>
</ul>
</div>
<div id="errorMessage"></div>
<div id ="newCltDiv">
<input id= "newClt" type="text" placeholder="Add a new client">
<button id="addCltBtn"> Add Client</button>
</div>
<br>
<br>
<div id="cltListDiv">
<select id="cltList">
<option>Select an existing client</option>
</select>
<button id="cltSelect">Select Client</button>
</div>
<br>
<br>
<script type="text/javascript">
var clientArray = [];
var clientInput = document.getElementById("newClt");
var sel = document.getElementById("cltList");
clientArray.push("box");
$("#addCltBtn").click(function(){
var found = $.inArray(clientInput, clientArray);
if(found >= 0) {
//Element was found update errorMessage div
$(errorMessage).html("This Client Already Exists");
} else{
clientArray.push(clientInput.value);
console.log("Objects: " + clientArray.join(", "));
updateDropList(clientInput.value);
}
});
function updateDropList(value){
var opt = document.createElement('option');
opt.innerHTML = value;
opt.value = value;
sel.appendChild(opt);
}
//test
clientArray.push("soccer");
console.log(clientArray);
</body>
</html>
最佳答案
您需要关闭脚本... </script>
并检查值...
var found = $.inArray(clientInput.value, clientArray);
关于javascript - jQuery 数组按下按钮单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30067189/