External jQuery simply not executing

十年热恋 提交于 2019-12-02 16:08:05

问题


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);


来源:https://stackoverflow.com/questions/12808434/external-jquery-simply-not-executing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!