无法使JS函数正常工作

Can't get JS function working properly

本文关键字:工作 常工作 JS 函数      更新时间:2023-09-26

我有这个带有引导程序的表单,但我找不到为什么它不能正常工作,我不知道为什么。

>>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <link href="css/bootstrap-theme.css" rel="stylesheet" type="text/css"/>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
    <link href="css/corrections.css" rel="stylesheet" type="text/css"/>
    <script src="js/JQuery-2.1.1-min.js" type="text/javascript"></script>
    <title></title>
</head>
<body>
-

-在这里>代码

</body>

网页>>

<div class="col-lg-4">
        <form class="form-inline well">
            <div class="form-group">
                <label class="sr-only" for="text">Some label</label>
                <input id="text" type="text" class="form-control" placeholder="Text here">
            </div>
            <button type="submit" class="btn btn-primary pull-right">Ok</button>
            <div class="alert alert-danger" style="display:none">
                <h4>Error</h4>
                Required amount of letters is 4
            </div>
            <div class="success alert-success" style="display:none">
                <h4>Success</h4>
                You have the required amount of letters
            </div>
        </form>
    </div>

JS>>

 <script>
        $(function () {
            $("form").on("submit", function () {
                if ($("input").val().length < 4) {                    
                    $("div.form-group").addClass("has-error");
                    $("div.alert").show("slow").delay(4000).hide("slow");
                    return;    
                } else if ($("input").val().length > 3) {
                    $("div.form-group").addClass("has-success");
                    $("div.success").show("slow").delay(4000).hide("slow");
                    return;   
                }
            });
        });
    </script>

警报类每次都显示,知道为什么吗?

这里使用$("input")是不寻常的。该选择器将拉回页面上所有<input> s 的元素,这几乎肯定不是您的意思。(如果页面上还有其他input,您可能会得到您所描述的内容。使用更精确的选择器,如 $("#text") ,也许使用 debug 输出 val().length 的值,以便您知道正在评估的内容。

(附带说明一下,"text"对于文本输入来说不是一个非常有用的名称,而你的else-if似乎是多余的,但它们可能不会在你的代码中引起问题。