开发者

'Object expected' using external JS

开发者 https://www.devze.com 2023-03-02 03:40 出处:网络
I have a开发者_高级运维 bit of code that works fine if it is added to a script tag on a page. I\'ve moved it into a seperate JS file (in the same folder as the HTML page) but I get an \'Object expecte

I have a开发者_高级运维 bit of code that works fine if it is added to a script tag on a page. I've moved it into a seperate JS file (in the same folder as the HTML page) but I get an 'Object expected' error anytime I try to call it.

This is my HTML page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
    <script type="text/javascript" src="Jscript1.js" />
    <script type="text/javascript">
        function t()
        {
            nsTest.test();
        }

        function t2()
        {
            nsTest.test2();
        }
    </script>
</head>
<body>
    <input type="button" value="test" onclick="t()" />
    <input type="button" value="test2" onclick="t2()" />
</body>
</html>

and this is my JS file:

var nsTest = function ()
{
    var test = function ()
    {
        alert('nsTest.test');
    }

    var test2 = function ()
    {
        alert('nsTest.test2');
    }

    return {
        test: test,
        test2: test2
    }
} ();

I'm sure that I'm missing something really simple and obvious but I'm pretty new to JS and I've been going round in circles for a couple of hours at this point.

Can somebody please let me know what I'm doing wrong?

Thanks,

David


<script type="text/javascript" src="Jscript1.js" />

is XML not HTML.

So you don't have a complete script tag, which can screw up the definitions in the following script tag.

Change it to

<script type="text/javascript" src="Jscript1.js"></script>

If that doesn't solve the problem (i.e. if that DTD is a real XHTML DTD), then "JScript1.js" is not being served properly. Maybe try loading it in your browser to check that it's being served, and served with a mime-type like text/javascript.


(function nsTest (){
    var test = function (){
      alert('nsTest.test');
    }

    var test2 = function (){
      alert('nsTest.test2');
    }

return {
    test: test,
    test2: test2
}
}) ();

you must enclose your function in parentheses when doing immediate call.


I found this looking for help with the same problem. In my case the issue was that my tag had type="application/javascript" instead of type="text/javascript".

That worked in most browsers but made IE 8 error out with "Object Expected".

type="text/javascript" is the correct attribute.

Hope that helps someone.

0

精彩评论

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

关注公众号