LoginSignup
3
4

More than 5 years have passed since last update.

JS初心者の私が「ん!?」ってなったとこ1:クオート「"」と「'」の違い

Last updated at Posted at 2015-01-23

なんの目的もなくJavaScriptを学び始めて3日。ウェブでいろいろ調べながら、お遊びしていて詰まったところを、備忘録として書いていきます。

(ほんとに初心者なので、)間違っている部分がありましたら、是非ともご指摘下さい。m(_ _)m

ソース

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
  <meta charset="utf-8">
  <title>jQuery Practice</title>
  </head>
  <body>
    <p>
      Hello World.
    </p>
    <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="jqsample.js"></script>
  </body>
</html>
jqsample.js
$(function() {
  $("p").html("<a href="http://google.com">Google</a>");  
})

ん!?

Google Chrome JavaScript Console上でエラーがでる。

Uncaught SyntaxError: Unexpected string

解決

あたりまえすぎるけど、ダブルクオート4つのせいで、真ん中のクオートが抜けてしまう。

jqsample.jsの「.html()」内のクオートをダブル(")からシングル(')にすると解決。

jqsample.js
$(function() {
  $('p').html('<a href="http://google.com">Google</a>');  
})

クオートの作法をちゃんと学び直そう

よくよく調べてみるとGoogle JavaScript Style Guideの「文字列」の節に、

文字列
" よりも ' を使ってください.
ダブルクオートよりもシングルクオートを使ってください. そのほうが HTML を含む文字列を作る際に便利です.

とありました。

多くのサイトでは、(役割的に)ダブルとシングルには大きな差はないと説明されていますが、JSではシングルクオート癖をつけといた方が良さそうですね。

3
4
3

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
3
4