JavaScript not working on external file

前端 未结 4 1849
孤城傲影
孤城傲影 2021-01-13 01:01

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

$(\'a.tocenter[href*=#]\').click( function() {
    if (location.pathname.replace(/^\\//,\'\') ==          


        
相关标签:
4条回答
  • 2021-01-13 01:36

    It basically tells your browser to run script after all DOM nodes are ready, i.e. downloaded and rendered.

    0 讨论(0)
  • 2021-01-13 01:47

    Try adding the script tag to the bottom of your html page instead of in the header. That is done for performance reasons that way your page appears as fast as possible and the extra javascript stuff is loaded afterwards.

    You can read more about this at : How does the location of a script tag in a page affect a JavaScript function that is defined in it?

    0 讨论(0)
  • 2021-01-13 01:48

    Wrap the content inside your file in

    $(function(){
    //js goes here
    });
    

    or put the reference to the file at the bottom of your page

    this allows the DOM to load before executing your script.

    0 讨论(0)
  • 2021-01-13 01:54

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

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

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

    or 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>
    

    Another way is to use 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
    });
    

    Have a look about it: http://api.jquery.com/on/

    0 讨论(0)
提交回复
热议问题