无法使用jQuery

时间:2015-04-27 08:58:15

标签: javascript jquery

当浏览器加载js文件时,它正在使用document.getElementById("name")

但是当我改为jQuery样式($("#name"))时,该特定元素似乎不再起作用了。

这就是我在HTML中编写脚本文件的方法(在结束体标记的正上方)

<script src="http://code.jquery.com/jquery-latest.min.js"> </script>
<script src="js/form.js"></script>
</body>

有谁知道为什么jQuery不起作用?

编辑:

它只是简单的代码,将所有document.getElementById替换为$。 但是既然你问过,这是我用过的原始js代码:

function formValidation() {
    var name = document.getElementById("name"),
        email = document.getElementById("email"),
        phone = document.getElementById("phone"),
        message = document.getElementById("message"),
        nameRe = /[a-zA-Z]/,
        emailRe = /^[a-zA-Z0-9._]+@[a-zA-Z0-9.]+\.[a-zA-Z]{2,4}$/,
        phoneRe = /[0-9]/,
        messageError = "";

    document.getElementById("frmContact").onsubmit = function () {
        messageError = "";

        // Validation for name, email and phone, using regular expression
        if (!nameRe.test(name.value)) {
            messageError = errorHighlight(name, "Invalid name");
        } else if (!emailRe.test(email.value)) {
            messageError = errorHighlight(email, "Invalid email");
        } else if (!phoneRe.test(phone.value)) {
            messageError = errorHighlight(phone, "Invalid phone");
        } else if (message.value.length <= 50) {
            messageError = errorHighlight(message, "Message must be at least 50 characters");
        }

        // form validation
        if (messageError !== "") {
            document.getElementById("errorMessage").innerHTML = messageError;
            return false;
        }
        return true;
    };
}

2 个答案:

答案 0 :(得分:1)

使用.val()例如:name.val()$("#name").val()

if (!nameRe.test(name.val())) {
            messageError = errorHighlight(name, "Invalid name");
        } else if (!emailRe.test(email.val())) {
            messageError = errorHighlight(email, "Invalid email");
        } else if (!phoneRe.test(phone.val())) {
            messageError = errorHighlight(phone, "Invalid phone");
        } else if (message.val().length <= 50) {
            messageError = errorHighlight(message, "Message must be at least 50 characters");
        }

答案 1 :(得分:-1)

以下如何使用它作为一个小例子:

<!DOCTYPE html>
<html lang="de">
    <head>
        <title>Welcome</title>
    </head>
    <body>
        <h1>It Works!</h1>
        <div id="changethat"></div>
        <script src="http://code.jquery.com/jquery-latest.min.js"> </script>
        <script>
            (function($,undefined){
                $('#changethat').html('Changed!');
            })(jQuery);
        </script>
    </body>
</html>

JSFiddle:http://jsfiddle.net/qxamct1n/1/