0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Uncaught SyntaxError: Illegal break statementエラーについて

Last updated at Posted at 2023-02-27

ソースコード

こちらがサンプルソースコードです。

index.html
<!DOCTYPE html>
<html lang="js">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>練習</title>
</head>
<body>
    <button type="button" id="btn" onclick=clickBtn()>練習</button>
    <p id="test"></p>
    <p id="test2"></p>
</body>
<script src="index.js"></script>
</html>
index.js
const btn = document.getElementById('btn')
const test = document.getElementById('test')
const test2 = document.getElementById('test2')
const clickBtn = () => {
    test.innerHTML = "1";
    break;
    test2.innerHTML = "2";    
}

エラー分はこちらです。

Uncaught SyntaxError: Illegal break statement

原因

breakは、for 文や、while 文などでしか使用できないためです。

解決策

breakの代わりにreturnを使う。

index.js
const btn = document.getElementById('btn')
const test = document.getElementById('test')
const test2 = document.getElementById('test2')
const clickBtn = () => {
    test.innerHTML = "1";
    return;
    test2.innerHTML = "2";    
}

こうすることで、画面に「1」が表示されるはずです。
以上になります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?