javascript - jQuery 数组按下按钮单击

标签 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>

最佳答案

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

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

关于javascript - jQuery 数组按下按钮单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30067189/

相关文章:

JavaScript canvas : when clearing with context. clearRect,一切都在下一次绘制时重现

Jquery + Css 拖放偏移问题

Javascript 和移动浏览器宽度问题

php - 在激活提交表单之前检查 jquery 表单?

php - mysql插入数据时数组使用和bindParam使用有什么区别?

javascript修改字符串数组的子索引

javascript - 为什么当我下载我的数组并尝试获取它的长度时,它只是吐出数组的字节数

javascript - Google Chrome 用户脚本引用 window.open

javascript - 如何在 ruby​​ 中使用 javascript 中的变量?

javascript - html 文本框转换的简单 Javascript。两次都不起作用