JavaScript无法处理外部文件 [英] JavaScript not working on external file

查看:107
本文介绍了JavaScript无法处理外部文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在HTML文档中使用此代码时,它就起作用了:

When I use this code inside my HTML document it's working:

$('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;}
    }
});

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

If I try to put this code inside an external JavaScript file and then link it with:

<script src="js/main.js"></script>

它不起作用,要使其起作用,我必须将其包装在里面:

It's not working, to let it work I had to wrap it inside:

$( window ).load(function() {
    ...
});

如果我这样做,那就行了.

If I do this it works.

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

I'm a total newbie in JavaScript/jQuery, is this normal or am I doing something wrong? Why is it behaving like that? Is it a good practice to do that?

将其保存在外部文件中的唯一目的是保持代码整洁易懂.

The only purpose of having it in an external file is for keeping the code clean and understandable.

推荐答案

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

You're attaching an event handler to an element using .click(), so it needs to be there at this point.

如果您检查page ready,则可以保证:

This can be guaranteed if you check for the page ready:

$(function() {
    // your code
}); 

window load:

$(window).load(function() {
    // your code
});

,或者如果您将脚本保留在页面中,请在其结尾:

, or if you keep the script in the page, at its end:

    <script type="text/javascript">
        // your code
    </script>
</body>

另一种方法是使用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
});

对此进行查看: http://api.jquery.com/on/

这篇关于JavaScript无法处理外部文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆