元のメッセージ
# jQuery入門ガイド jQueryは、JavaScriptをより簡単に書けるようにするライブラリです。HTML要素の操作、イベント処理、アニメーションなどを直感的に実装できます。 ## jQueryとは jQueryは「write less, do more」(少ない記述で、より多くのことを)をモットーとするJavaScriptライブラリです。複雑なJavaScriptコードを簡潔に書くことができます。 ### jQueryの特徴 - **シンプルな構文**: CSS セレクターを使った要素の選択 - **クロスブラウザ対応**: ブラウザの違いを意識せずに開発可能 - **豊富な機能**: DOM操作、イベント処理、アニメーション、Ajax通信 - **チェーンメソッド**: 複数の処理を連続して実行可能 ## jQueryの導入 ### CDNを使用した導入方法 ```html
要素 // 属性で選択 $("[data-role='button']") // data-role="button"を持つ要素 // 複合セレクター $("div.myClass") // class="myClass"を持つdiv要素 $("#container p") // id="container"内のすべてのp要素 $("li:first") // 最初のli要素 $("li:last") // 最後のli要素 $("li:eq(2)") // 3番目のli要素(0から開始) }); ``` ## DOM操作 ### テキストとHTMLの操作 ```html
元のメッセージ
```
```javascript
$(function() {
// 属性の操作
$("#changeImage").click(function() {
// 属性の取得
var currentSrc = $("#myImage").attr("src");
console.log("現在の画像: " + currentSrc);
// 属性の設定
$("#myImage").attr({
"src": "image2.jpg",
"alt": "画像2"
});
});
// CSS操作
$("#toggleStyle").click(function() {
// CSSクラスの追加/削除
$("#myImage").toggleClass("highlight");
// 直接CSSスタイルの設定
$("#myImage").css({
"border-radius": "10px",
"transition": "all 0.3s ease"
});
});
});
```
### 要素の作成と削除
```html
ボタンがクリックされました!
"); }); // 入力イベント $("#textInput").on("input", function() { var inputValue = $(this).val(); $("#output").html("入力中: " + inputValue + "
"); }); // マウスイベント $("#mouseArea") .mouseenter(function() { $(this).css("background-color", "yellow"); $("#output").append("マウスが入りました
"); }) .mouseleave(function() { $(this).css("background-color", "lightblue"); $("#output").append("マウスが出ました
"); }); // フォーカスイベント $("#textInput") .focus(function() { $(this).css("border", "2px solid green"); }) .blur(function() { $(this).css("border", "1px solid #ccc"); }); }); ``` ### フォームイベント ```html ``` ```javascript $(function() { // フォーム送信イベント $("#myForm").submit(function(e) { e.preventDefault(); // デフォルトの送信動作を防ぐ // フォームデータの取得 var formData = { name: $("#name").val(), email: $("#email").val(), age: $("#age").val() }; // バリデーション if (formData.name === "" || formData.email === "") { $("#formOutput").html("名前とメールは必須です
"); return; } // 送信成功時の処理 $("#formOutput").html( "名前: " + formData.name + "
" + "メール: " + formData.email + "
" + "年齢: " + formData.age + "
" ); // フォームをリセット this.reset(); }); // 選択変更イベント $("#age").change(function() { var selectedAge = $(this).val(); if (selectedAge) { $("#formOutput").append("年齢層が選択されました: " + selectedAge + "
"); } }); }); ``` ## アニメーション ### 基本的なアニメーション ```html読み込み中...
"); }, success: function(data) { $("#ajaxResult").html( "タイトル: " + data.title + "
" + "内容: " + data.body + "
" ); }, error: function(xhr, status, error) { $("#ajaxResult").html("エラーが発生しました: " + error + "
"); } }); }); // POST リクエスト $("#sendData").click(function() { var postData = { title: "jQueryからの投稿", body: "これはjQueryのAjaxで送信されたデータです", userId: 1 }; $.ajax({ url: "https://jsonplaceholder.typicode.com/posts", method: "POST", data: JSON.stringify(postData), contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { $("#ajaxResult").html( "作成されたID: " + response.id + "
" + "タイトル: " + response.title + "
" ); }, error: function(xhr, status, error) { $("#ajaxResult").html("送信エラー: " + error + "
"); } }); }); }); ``` ### 簡略化されたAjaxメソッド ```javascript $(function() { // $.get() - GETリクエストの簡略形 $("#simpleGet").click(function() { $.get("https://jsonplaceholder.typicode.com/users/1") .done(function(data) { console.log("成功:", data); }) .fail(function() { console.log("失敗"); }); }); // $.post() - POSTリクエストの簡略形 $("#simplePost").click(function() { $.post("https://jsonplaceholder.typicode.com/posts", { title: "簡単な投稿", body: "$.post()を使用", userId: 1 }) .done(function(data) { console.log("投稿成功:", data); }); }); // $.getJSON() - JSON取得の簡略形 $("#getJson").click(function() { $.getJSON("https://jsonplaceholder.typicode.com/posts/1", function(data) { console.log("JSONデータ:", data); }); }); }); ``` ## 実践的な例:ToDoアプリ ```html総タスク数: 0
完了済み: 0