前提・実現したいこと
ボタンクリック時に入力されている値を取得した後に、If文を使い以下のように背景色を変更する。
赤が入力されていたら:赤
青が入力されていたら:青
それ以外が入力されていたら:緑
発生している問題・エラーメッセージ
背景色が変わらない。
コード <!DOCTYPE html> <html lang="ja"> <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"> <link rel="stylesheet" href="style.css"> <script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script> <title>Document</title> </head> <style> .example { display: block; margin-top: 100px; margin-left: 100px; text-align: left; } .box { width: 500px; height: 500px; background-color: gray; } </style> <body> <div class="example"> <input type="text" id="value"> <input type="button" id="button" value="ボタン"> </div> <div class="box" id="box1"></div> </body> <script src="index.js"> $(function(){ $('#button').on("click", function () { var text = $('#value').val(); if(text === '赤'){ $('#box').css('background-color','#ff0000'); } if(text === '青'){ $('#box').css('background-color','#0000ff'); } if(text === '緑'){ $('#box').css('background-color','#008000'); } }); }); </script> </html>
回答2件