スニペットとは、よく使われるコードを断片化して名前をつけたもののことです。
今回はCODROPSでjavascriptとjQueryのスニペットがまとめられていたのでご紹介します。
右クリック禁止。
$(document).ready(function(){ $(document).bind("contextmenu",function(e){ return false; }); });
すべてのチェックボックスのチェックするしないを一括で切り替え。
var tog = false; // or true if they are checked on load $('a').click(function() { $("input[type=checkbox]").attr("checked",!tog); tog = !tog; });
なんらかのキーが押されたことを判定。
$(function() { $(document).keypress(function(e){ switch(e.which){ // "ENTER" case 13: alert('enter pressed'); break; // "s" case 115: alert('s pressed'); break; (...) } }); });
XMLのパース。
XMLファイル(file.xml):
<?xml version="1.0" ?> <result> <item> <id>1</id> <title>title1</title> <description>desc1</description> </item> <item> <id>2</id> <title>title2</title> <description>desc2</description> </item> <!-- ... --> </result>jQuery:
$.get('file.xml',{},function(data){ $('item',data).each(function(){ var $this = $(this); var id = $this.find('id').text(); var title = $this.find('title').text(); var description = $this.find('description').text(); //do something ... }); });
参照元にはPart1からPart4まで、さらに多くのスニペットがあります。
Some Useful JavaScript & jQuery Snippets | Codrops
