-1

For some reason when I try and run a simple jQuery code it won't work. I beleive the code is correct and it's like my file isn't linked correctly. It also won't work on other pages with different code so I'm thinking it must be something with the way that jQuery is linked. My code is:

<!DOCTYPEhtml PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.7.2.min"></script>
<script type="text/javascript">
$('#toggle_message').click(function() {
    var value = $('#toggle_message').attr('value');
    $('#message').toggle('fast');

    if (value == 'Hide') {
        $('#toggle_message').attr('value', 'Show');
    } else if (value == 'Show') {
        $('#toggle_message').attr('value', 'Hide');
        }
    }
});
$('#toggle_message').click();
</script>
</head>
<body>
<input type="button" value="Hide" id="toggle_message" />
<p id="message">This is a paragraph that will disappear</p>
</body>
</html>

Any help is appreciated. Also, my jQuery file is only 4 lines long.. Is that normal?

4

2 回答 2

5

我怀疑你忘记了.jsjQuery 的文件名。它应该是:

<script type="text/javascript" src="jquery-1.7.2.min.js"></script>

另外,是的,文件只有很少的行是正常的。它是压缩的,每一行都很长。

此外,正如 Nudier 在评论中提到的,在页面加载之前绑定到元素将不起作用。您可能希望延迟绑定,直到页面加载:

$(function() {
    $('#toggle_message').click(function() {
        // ...
    });
    $('#toggle_message').click();
});
于 2012-05-03T03:36:59.987 回答
0

尝试将您的 JQUERY 代码包装在 .ready 函数中。另外,如上所述,链接的js可能不正确。如果需要,请随意尝试以下操作并将 Jquery 源更改为您的本地副本。通常我只使用来自:http ://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js 的 src

 <!DOCTYPEhtml PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html>
    <head>
    <title></title>
    <script src="" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('#toggle_message').click(function() {
            var value = $('#toggle_message').attr('value');
            $('#message').toggle('fast');

            if (value == 'Hide') {
                $('#toggle_message').attr('value', 'Show');
            } else if (value == 'Show') {
                $('#toggle_message').attr('value', 'Hide');
                }
        });

        $('#toggle_message').click();
    });


    </script>
    </head>
    <body>
    <input type="button" value="Hide" id="toggle_message" />
    <p id="message">This is a paragraph that will disappear</p>
    </body>
    </html>
     $('#toggle_message').click();
    });
于 2012-05-03T03:56:57.600 回答