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 5 years have passed since last update.

jQueryでイベントを使ってみよう

Posted at

今週はjQueryについて勉強しました。
jQueryとは、JavaScriptという言語でつくられたライブラリです。
JavaScriptを使わないとできないようなこともjQueryを使えば簡単に実装することができます。
具体的には、クリックしたら文字に取り消し線が入るなど、ページを移動することなく様々な「動き」をつけることができます。

jQueryの読み込み方

JQueryは読み込みをしないと使えません。
今回はウェブページから読み込む方法を紹介します。

index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

このように、HTMLのbody要素の中に記述します。

イベント

今回はよく使うマウスイベントのクリックメソッドを例に紹介します。

index.php
<script>
        $(function() {
            $('#checkbox').click(function() {
                if ($(checkbox).is(":checked")) {
                $(checkbox).closest("tr").css("text-decoration", "line-through");
                }
                else {
                $(this).closest("tr").css("text-decoration", "none");
                }
            });
        });
    </script>

このようなコードを書きましたので、1つずつ解説していきます。
書き出しは、$(function(){ です。
イベントを適用する要素を $('#checkbox')で選択します。
要素に対するメソッドは.click(function() { です。
クリックしたことで実行するイベントは、if以下で条件分岐しています。
要素である $('#checkbox')にクリックすることで、.is(":checked")というイベントで要素にチェックが入ります。
その場合、HTMLの行の要素であるtrの値を取得してcssで取り消し線を追加します。
クリックしない場合は、tr要素に取り消し線は入りません。

まとめ

今回は、jQueryのイベントの方法を中心にアウトプットをしました。
今後も学習を続けて行きたいと思います。

 

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?