SyntaxError: expected expression, got '<

2019-04-20 23:47发布

I know this is asked a few times on S.O.

but none of the answers seem to match my situation . So, I have a a basic Html page which tries to use an external JS. The JS file tries to change the content of a paragraph defined in the HTML on a button click, but does not seem to work.

I see the following errors in console :

1)SyntaxError: expected expression, got '<'

2)ReferenceError: change is not defined

JSFiddle showing exact source?(except that & tags are removed as jsfiddle - http://jsfiddle.net/p9ko4yde/

HTML Code :

<h1> Numbers with external script:) </h1>
<p id="number">1</p>
<button type="button" onclick="change()">Toggle between 1 and 2</button>

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



</body>
</html>

JS Code :

<script type="text/javascript">
    function change(){
        var number = document.getElementById('number').innerHTML;
        if(number == '1'){
            document.getElementById('number').innerHTML='2';
        }
        else{
            document.getElementById('number').innerHTML='1';
        }
    }
</script>

File Structure is as below:enter image description here

4条回答
Rolldiameter
2楼-- · 2019-04-20 23:54

The syntax error is because you have <script> tags in your JS file. When you put JavaScript in its own file like that, you don't need to surround it with script tags; that's HTML, and this is a JavaScript file.

The reference error is happening because, due to the syntax error, the JS file isn't executing correctly and so the change function never got created -- fixing the syntax error should also resolve this.

查看更多
我只想做你的唯一
3楼-- · 2019-04-21 00:02

You don't need the <script> tags when in an external .js file. Use these tags to embed a script inside HTML only.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-04-21 00:02

Sometimes this error happens when the Javascript referenced file doesn't exist. Make sure that the file name is correct and you have the file in place. I know your problem is solved but maybe this answer solves someone else's :)

查看更多
我命由我不由天
5楼-- · 2019-04-21 00:13

In a js file, you do not use the HTML to declare that it is a js file. So, you can drop the script tag in myScript and change it to this :

function change(){
    var number = document.getElementById('number').innerHTML;
    if(number == '1'){
        document.getElementById('number').innerHTML='2';
    }
    else{
        document.getElementById('number').innerHTML='1';
    }
}
查看更多
登录 后发表回答