Skip to content

Instantly share code, notes, and snippets.

@siroken3
Created September 20, 2012 03:03
Show Gist options
  • Select an option

  • Save siroken3/3753718 to your computer and use it in GitHub Desktop.

Select an option

Save siroken3/3753718 to your computer and use it in GitHub Desktop.
jQuerypluginハンズオンの資料
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Sample jQuery Plugin</title>
</head> <body>
<input type="text"/>
<ul>
<li>abc</li> <li>def</li>
<li>jquery</li>
</ul>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// (function($){ '$'が他のscriptとかぶらないようにするプラグインを書くための工夫
// })(jQuery);
//
(function($){
// $.fn.hoge でプラグイン登録
$.fn.listFilter = function(inputSelector) {
// thisはulを指す
this.find('li').each(function(index, elm) {
// ここのthisはliをさします
//console.log(arguments); // 引数になにがわたってきているか見れる
$(elm).attr('data-list-filter', $(elm).text().toLowerCase());
});
var $targetLi = this.find('li');
var $input = $(inputSelector); // jQuery objectに変換しているので$始まりの変数にした
$input.keyup(function() {
var text = $input.val().toLowerCase();
if (text === '') {
$targetLi.show();
return; } $targetLi.hide();
$targetLi.filter('[data-list-filter*="' + text + '"]').show(); // *= はcssで"含まれる"を意味する
});
return this;
}
})(jQuery);
</script> <script> // HTMLの最後の方にかいてあるのでDOMが既に構築されている   // $()で囲むのは他のスクリプトが動作してしまうため。$(init)でDOMとかを読み込んだりする
$(function(){
$('ul').listFilter('input');
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment