简体   繁体   English

检查用户名是否已经存在,没有 ajax 或 php,只是纯 js

[英]Check if username already exists, no ajax or php, just pure js

Here is the code:这是代码:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript"> 
        function submit() 
        {
            var ul = document.getElementById("names");
            var name = document.getElementById("name").value;

            var i = 0, flag = 0;
            var allNames = [];
            if (allNames.length == 0) 
            {
                allNames[0] = name;
            }
            else 
            {
                if (allNames.includes(name))
                {
                    alert("Name already exists.");
                    return -1;
                }
                else 
                {
                    allNames[i++] = name;
                }
            }
            var li = document.createElement("li");
            li.innerHTML = name;

            ul.appendChild(li);
            document.getElementById("name").value = "";
        }
    </script>
</head>
<body>
    <input type="text" id="name">
    <button onclick="submit()">Submit</button>
    <div>
        <h2>Usernames</h2>
        <ul id="names"></ul>
    </div>
</body>
</html>

Is there any way to check if a username already exists and therefore block the new entry, only using javascript?有没有办法检查用户名是否已经存在并因此阻止新条目,仅使用 javascript?

I've tried also moving the initialization of the array outside of the function but it doesn't work that way either...我也尝试过将数组的初始化移到 function 之外,但它也不起作用......

Yes, just declare the allNames variable outside of your function.是的,只需在 function 之外声明allNames变量。 You currently create it with an empty array each time you call the submit function.您当前每次调用提交 function 时都会使用空数组创建它。

You also have an issue because your i is set to 0 every time.您还有一个问题,因为您的i每次都设置为 0。 Just use .push if it is not included ( instead of trying to specify the index ).如果不包含它,只需使用.push而不是尝试指定索引)。

 var allNames = []; function submit() { var ul = document.getElementById("names"); var name = document.getElementById("name").value; if (allNames.includes(name)) { alert("Name already exists."); return -1; } else { allNames.push(name); } var li = document.createElement("li"); li.innerHTML = name; ul.appendChild(li); document.getElementById("name").value = ""; }
 <input type="text" id="name"> <button onclick="submit()">Submit</button> <div> <h2>Usernames</h2> <ul id="names"></ul> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM