jQuery .ready无法正常工作

时间:2016-04-16 00:28:54

标签: javascript function

有谁能告诉我为什么这段代码不起作用?我有一个输入,我试图检查天气与否,输入是"开始"。所以我做......无论什么都没有用 - 甚至不是。但我是新的,所以我不知道问题是什么。

HTML

<form id="inputForm" onsubmit="return false;">
    <input id="input" type="text" size="30" autofocus="autofocus" maxlength="100" autocomplete="off"/>
</form>

JS:

var input = "";

$(document).ready(function() {
    $("#inputForm").submit(function() {
    input = $("#input").val().toUpperCase();

    if (input === "START") {
        alert("worked");
    }

    $("#command_input").val("");
})
});

4 个答案:

答案 0 :(得分:2)

我怀疑您的网页中没有包含jQuery。您可以通过添加

来导入它
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

代码的script代码之前。 (https://code.jquery.com/jquery还有更多jQuery CDN)

你真的不需要jQuery来做到这一点。这是普通的JS等效代码working here

var input = "";
document.body.onload = function() {
    document.getElementById("inputForm").addEventListener("submit", function() {
        input = document.getElementById("input").value.toUpperCase();
        if (input === "START") {
            alert("worked");
        }
        document.getElementById("command_input").value = "";
    });
};

答案 1 :(得分:1)

在这里查看代码后:https://jsfiddle.net/cu7tn64o/1/

似乎工作正常!正如其他评论者所提到的,这很可能是因为你没有在你的html文件中包含jQuery,如下所示:

<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>

https://code.jquery.com/

答案 2 :(得分:1)

  1. 首先在html文件中使用脚本标记包含jquery文件。

  2. 使用jquery提交表单,或者在我使用按钮提交的以下情况下提交表单。提交值取自输入字段并进行比较。

  3. &#13;
    &#13;
    var input = "";
    
    $(document).ready(function() {
        $("#inputForm").submit(function() {
        input = $("#input-value").val().toUpperCase();
    
        if (input === "START") {
            alert("worked");
        }
        else
        {
        alert("sorry");
        }
    
        $("#command_input").val("");
    })
    });
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="inputForm" onsubmit="return false;">
        <input id="input-value" type="text" size="30" autofocus="autofocus" maxlength="100" autocomplete="off"/>
        <input type="submit" name="submit" value="submit" />
    </form>
    &#13;
    &#13;
    &#13;

答案 3 :(得分:0)

如果从事件处理程序返回false,则事情应该有效。

var input = "";

$(document).ready(function() {
    $("#inputForm").submit(function() {
        input = $("#input-value").val().toUpperCase();

        if (input === "START") {
            alert("worked");
        } else {
            alert("sorry");
        }

        $("#command_input").val("");

        // You have to return false HERE to prevent the default action of a                     
        // form -- send a request to a server, that is

        return false;
    });
});