JavaScript无法处理外部文件

pwn*_*ack 5 javascript jquery external-js

当我在HTML文档中使用此代码时,它正在工作:

$('a.tocenter[href*=#]').click( function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
    && location.hostname == this.hostname) {
    var $target = $(this.hash);
    $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
    if ($target.length) {
    var targetOffset = $target.offset().top;
    $('html,body').animate({ scrollTop: targetOffset - ( $(window).height() - $target.outerHeight(true) ) / 2 }, 1000);
    return false;}
    }
});
Run Code Online (Sandbox Code Playgroud)

如果我尝试将此代码放在外部JavaScript文件中,然后将其链接到:

<script src="js/main.js"></script>
Run Code Online (Sandbox Code Playgroud)

它不起作用,让它工作我必须把它包装进去:

$( window ).load(function() {
    ...
});
Run Code Online (Sandbox Code Playgroud)

如果我这样做有效.

我是JavaScript/jQuery的新手,这是正常的还是我做错了什么?为什么它表现得那样?这样做是一种好习惯吗?

在外部文件中使用它的唯一目的是保持代码清洁和易懂.

mel*_*cia 9

您正在使用事件处理程序附加到元素.click(),因此它需要在此处.

如果您检查以下内容,可以保证这一点page ready:

$(function() {
    // your code
}); 
Run Code Online (Sandbox Code Playgroud)

或者window load:

$(window).load(function() {
    // your code
});
Run Code Online (Sandbox Code Playgroud)

,或者如果您将脚本保留在页面中,最后:

    <script type="text/javascript">
        // your code
    </script>
</body>
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用delegation:

$(selector_for_element_that_will_surely_be_there).on(event, selector_for_element_receiving_the_event, function() {
    // your code
});

// ie:
$(document).on('click', 'a.tocenter[href*=#]', function() {
    // your code
});
Run Code Online (Sandbox Code Playgroud)

看一看:http://api.jquery.com/on/