External jQuery simply not executing

2019-03-04 03:50发布

问题:

The code below was fully working when it was placed inside <script></script> tags on the running page. I since moved the code to an outside .js file for organizational purposes which caused the code to stop working - nothing happens when certain events should be fired. I ensured that the script was being included on the given page, and furthermore, I ensured that the link was valid through "view-source" (when I clicked on the script's path, the script loaded in a new window).

The script declarations:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/main.js"></script>

So, what does my JS look like in this external file?

(function(){

$('#display-reply-box').click(function(){
    $(this).hide();
    $('#submit-reply-wrapper').show();
});

})(jQuery);

I removed most of the methods for readability, but that is how the file is setup. I ensured that there were no .js errors in the console, however, I did get the following errors regarding jQuery and Firelite

Failed to load resource: the server responded with a status of 404 (Not Found) http://getfirebug.com/releases/lite/skin/xp/pixel_transparent.gif Failed to load resource: the server responded with a status of 405 (Method Not Allowed) http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js

I would assume the above errors have something to do with the problem I'm experiencing, although I've had no luck getting them to disappear. At times the errors are there, other times they are not.

回答1:

It seems as though you're attempting to run something on an element that might not have loaded in the DOM. Try wrapping it in a DOM Ready event handler like this:

(function($) {
    $(document).ready(function() {
        $('#display-reply-box').click(function(){
            $(this).hide();
            $('#submit-reply-wrapper').show();
        });
    });
})(jQuery);