Project_OKI’s diary

エンジニアの勉強ブログ

jQuary、javascript学習2(id取得)

​​​jQuary,javascript学習2(id取得)

・目次

 

 1.目的

 ・jQuaryを使用し、htmlのid及びclassを取得する方法について記載する。

 ・idとclassの取得方法を理解する。

 

2.id及びclassの取得

// JQueryの記述方法(idを取得)
    $("#id名").コマンド();

 ・$:jQueryを示す

 ・コマンド:jQueryの命令

例:

$("#test1").click(function(){

 ・test1という名前のidを取得して、test1がクリックされたらfunctionを実行

 

// JQueryの記述方法(classを取得)
    $(".class名").コマンド();

 ・$:jQueryを示す

 ・コマンド:jQueryの命令

例:

$(".test2").click(function(){

 ・test2という名前のclassを取得して、test2がクリックされたらfunctionを実行

 

3.プログラムの作成(idとclassのクリック)

<!--   
    目的:Javascriptの基礎を作成する。
        Hellow側をクリックしたら、Hellow側の文字列をidクリックに文字を変更
        クラスクリックをクリックしたら、Hellow側の文字列をクラスクリックに文字を変更
-->

<!doctype html>
 <html lang="ja">
   <head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width" />
     <title>テストページ</title>
    <!-- JQuaryの追加 -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

     <style>
     </style>
     <script>
     	window.onload = function () {
     		$("#test1").click(function(){
     			$("#test1").text("idクリック");
     		})
     		$(".test2").click(function(){
     			$("#test1").text("クラスクリック");
     		})
		}
     </script>
   </head>
   <body>
     <p id= "test1">Hello</p>
     <p class="test2">クラス</p>
   </body>
 </html>

・実行結果(Hello又はクラスをクリックすると、文字列が変化する)

ーーーーーーーーーーーーーーーーーーー

Hello

クラス

ーーーーーーーーーーーーーーーーーーー

 

4.プログラム説明

・ <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

 →script src = でurlやファイル名を指定することにより、

  外部のjavascript(jQuaryなど)を使用できるようにする。

 

・$("#test1").click(function(){

 →jQuaryを使用

 →testという名前のクラスをクリックした時、関数を実行

 →.click() | jQuery 1.9 日本語リファレンス | js STUDIO

 

・.text("変更後の文字");

 →指定した要素に、指定したHTMLをセットする。

 →今回はtest1という名前のidを変更

 →.text() | jQuery 1.9 日本語リファレンス | js STUDIO

関連記事