开发者

Same JS external file, different html's, how to trigger different function when html's are loaded?

I would like to ask is someone could help me out with this doubt:

I got an external .js file with all the functions I use in some website. There are also different html docs with different content, of course, and I want to invoke a function to update s开发者_如何学编程ome content (the header and the selected items in some select fields within a form which aren't the same).

I know I can do this just using the onload event in the html body tag and calling different functions of the js file but I've read that's not the best approach, so my question is: how can I invoke different functions of the same js file from different html docs?

Thanks in advance!


file1.html:

<!doctype html>
<body>
....
<script src=file.js></script>
<script>
// some code
</script>
</body>

file2.html:

<!doctype html>
<body>
....
<script src=file.js></script>
<script>
// different code
</script>
</body>

You can also check the location or the DOM in your JavaScript but the above is as simple as it gets.

Other ways, in file.js:

if (location.href == 'something') {
    // do something
} else {
    // do something else
}

Or, using jQuery:

jQuery(document).ready(function($) {
    if ( $('h1').text() == 'Main Page' ) {
        $('nav').hide();
        $('#welcome').show();
    } else {
        // something ...
    }
});


Page type 1:

<html>
    <body class="one">
    ...Markup...
    </body>
</html>

Page type 2:

<html>
    <body class="two">
    ...Markup...
    </body>
</html>

jQuery:

$().ready(function()
{
    ...code for all pages...

    if($('body').hasClass('one'))
    {
        ...code for pages of type 1...
    }
    else if($('body').hasClass('two'))
    {
        ...code for pages of type 2...
    }

    ...code for all pages...
});

I'm far from being a JavaScript guru, so I don't know how you might do this in pure JS. As rsp says, you could also split your code into separate files - one for code that will be needed in all pages, and files with page specific code which are only loaded on the page where they're required.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜