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~上級編~

Last updated at Posted at 2020-05-31

プログラミングの勉強日記

2020年5月31日 Progate Lv.80

jQueryにおける関数

 共通部分を関数化することができる。同じ処理(全く同じコード)を関数としてまとめる。

$('.index-btn').click(function(){
 var slideIndex=...                 //共通部分の処理
});
$('.change-btn').click(function(){
 var slideIndex=...                 //共通部分の処理
});

 この共通部分の処理を関数としてまとめる。定義した関数をそれぞれのclickイベントの中で呼び出す。関数を呼び出すときはその関数名を記述するだけでいい。

$('.change-btn').click(function(){
 toggleChangeBtn();                 //関数の呼び出し
});

function toggleChangeBtn(){
  var slideInex=...
}
length

 jQueryオブジェクトの要素の個数を取得できる。

<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>jQuery</li>
</ul>
$('li').length; //結果は3
textメソッド

 前回紹介したように引数に指定した文字列を要素に「セット」するメソッドでもある。(https://qiita.com/mzmz__02/items/c7ebc268325d935436f9)
それだけでなく、textメソッドは引数を指定せずに用いると要素内の文字列を「ゲット」する。

<h1>Hello</h1>
<p>program</p>

〇文字列を書きかえる場合
$('h1').text('こんにちは'); h1要素内を引数の文字列で変更。
 
〇文字列を取得する場合
var text=$('p').text(); p要素ないの文字列「program」を取得する

htmlメソッドとcssメソッド

 こちらもtextメソッド同様にゲットして使うことができる。

<div id="main">
  <h1>Hello</h1>
</div>
h1{
  font-size:28px;
}

〇HTMLを習得する場合
 var html=$('main').html(); 「#main」内のHTML(<h1>Hello</h1>)を取得する
〇CSSプロパティを取得する場合
var fontSize=$('h1').css('font-size'); h1要素内のフォントサイズ(28px)を取得する

attrメソッド

 HTMLの属性はattrメソッドを用いて「ゲット」と「セット」ができる。第一引数に属性名、第二引数にその属性値を指定することで属性をセットできる。第二引数を指定しないとその造成の値を取得できる。

<h1>Hello</h1>
<a href="https://aiueo.com">リンク</a>

〇属性をセットする場合
&('h1').attr('id','title'); h1要素にtitleにidをセット
〇属性の値を取得する場合
 var url=$('a').attr('href'); a要素のhref属性の値(https://aiuo.com)を取得する。

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?