jQuery数组按下按钮点击

时间:2015-05-06 03:53:41

标签: javascript jquery arrays

我正在跟进上一个问题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>

1 个答案:

答案 0 :(得分:1)

您需要关闭脚本... </script>并检查值...

var found = $.inArray(clientInput.value, clientArray);