2
2

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を使うときの、読み込み方法を「body要素」に「hellw, world」とh1タグ出力することで確認してみる。

以下の様になる↓


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>jQuery-test01</title>
</head>
<body>


<script type="text/javascript">

$(function() {
	$('body').html('<h1>hello, world</h1>');
});

</script>

</html>

jq003.png

$ ---- jQueryという関数の別名

jQueryでは$という記号がたくさん出てきます。

例えば、、


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>jQuery-test02</title>
</head>
<body>

<div class="box">美浜ちよです。</div>

<script type="text/javascript">

$('.box').css('color', 'red');

</script>

</html>


jq002.png

  • $('.box').css('color', 'red');の部分は以下と全く同じ意味になります。

  • jQuery('.box').css('color', 'red');

違いは$jQueryになっている点です。jQueryを読み込むとjQueryという関数が使える様になります。このjQueryという関数の別名が$のことです。

ただ、ほとんどすべての場合で$を使っています。

$(function)() {}) ----- HTMLの読み込みを待って処理する

JavaScriptの場合window.onloadDOMContentLoadedで要素を取得できたが、複数の処理を設定するのにaddEventListenerを使うため、クロスブラウザ対応が出来ない弱点があった。

jQueryの場合$(function)() {})の記述で以下のような挙動が可能になる。

  • クロスブラウザで動作する
  • 画像のロードなどは待たずに、HTMLの構築が終わった時点で処理を開始する
  • 複数の処理を設定できる。
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?