犬飼たつきちのライフハック

#ライフハック #ソフトウェア #Webサービス #Python #docker …

このブログは、アフィリエイトプログラムやアドセンスを利用しています。

WordPress記事におけるJavaScript実装方法

この記事では、wordpressの記事内でJavaScriptを使用する方法を解説します。 記事内ではjQueryを使用していますが、jQuery以外のライブラリにも応用できる方法です。

ブロックエディタのカスタムHTMLを選択

じゃんけんのスクリプトを用意してみた

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <h1>じゃんけんゲーム</h1>
  <p>あなたの手を選んでください:</p>
  <button class="btn-hand" id="btn-gu">グー</button>
  <button class="btn-hand" id="btn-choki">チョキ</button>
  <button class="btn-hand" id="btn-pa">パー</button>
  <p id="result"></p>

  <script>
  $(function() {
    // じゃんけんの手
    const hands = ["グー", "チョキ", "パー"];

    // コンピュータの手をランダムで生成
    function getComputerHand() {
      return hands[Math.floor(Math.random() * hands.length)];
    }

    // 勝負判定
    function judge(yourHand, computerHand) {
      if (yourHand === computerHand) {
        return "あいこ";
      } else if ((yourHand === "グー" && computerHand === "チョキ") ||
               (yourHand === "チョキ" && computerHand === "パー") ||
               (yourHand === "パー" && computerHand === "グー")) {
        return "勝ち";
      } else {
        return "負け";
      }
    }

    // ボタンクリックイベント
    $(".btn-hand").click(function() {
      const yourHand = $(this).text();
      const computerHand = getComputerHand();

      // 結果を表示
      $("#result").text(`あなたの手:${yourHand}、コンピュータの手:${computerHand}、結果は:${judge(yourHand, computerHand)}`);
    });
  });
  </script>

これをカスタムHTMLブロックに貼り付ける。

実際の画面を確認する。

グーを押してみると

終わり

PR

wordpressレンタルサーバーを使うのがおすすめ

GMOグループさんの【ConoHa WING】 は要チェックです。