我正在尝试改进我编写的一些javaScript,以将元素插入数组(如果它们以前不在数组中)。然后,我希望该数组显示在选择字段中。我在 javascript 中完成了这一切,但我认为尝试在 jQuery 中做同样的事情对我自己来说将是一个有趣的练习。我想我已经很接近了,但由于某种原因,我的浏览器中的控制台给了我一个错误,如下所示:
"[Error] SyntaxError: Cannot use the keyword 'var' as a variable name. (anonymous function)"
这是到目前为止我的代码。我(按此顺序)包含了我对 jQuery 的尝试,然后包含了我的工作 javascript 代码(已注释掉),以及更新下拉列表的函数。我最终也会尝试在 jQuery 中重新创建该函数。谁能告诉我为什么会出现此错误,或者我在 jQuery 中做错了什么?谢谢。
var clientArray = [];
var clientInput = document.getElementById("newClt");
var sel = document.getElementById("cltList");
$("#addCltBtn").click(function(){
var found = $.inArray(clientInput, clientArray) > -1;
if(found >= 0) {
//Element was found update errorMessage div
$(errorMessage).html("This Client Already Exists");
} else{
clientArray.push(clientInput.value);
}
});
//
// document.getElementById("addCltBtn").onclick=function(){
//
// console.log(clientArray.length);
// if (!contains(clientArray,clientInput.value)) {
// clientArray.push(clientInput.value);
// console.log("Objects: " + clientArray.join(", "));
// updateDropList(clientInput.value);
// }
// else alert("You already have a client by that name!");
// }
function updateDropList(value){
var opt = document.createElement('option');
opt.innerHTML = value;
opt.value = value;
sel.appendChild(opt);
}
function contains(a, obj){
for(var i =0; i< a.length; i++){
if(a[i] === obj){
return true;
}
}
return false;
}
最佳答案
var found = $.inArray(clientInput, clientArray) > -1;
为什么要在这个声明中进行比较?这就是抛出你的错误的原因。您检查在其他地方找到的值是否大于或等于 0,因此删除 > -1 应该会使一切正常。
关于javascript - 数组按下按钮点击jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055946/