實用jquery代碼片段集合
加載google的jquery庫
- <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>
有利于加快加載速度(已經得到驗證)。
修改圖片src更新圖片
- $(imageobj).attr(‘src’, $(imageobj).attr(‘src’) + ‘?’ + Math.random() );
(這是很實用的技巧,曾經有人問明河,為什么他已經修改了圖片的src,但圖片沒變化呢?原因在于緩存,給圖片路徑后加個隨機數參數即可。
加載多張圖片,判斷加載完成狀態
- var totalimages = 10;
- var loadedimages = 0;
- $(“<img/>”).load(function() {
- ++loadedimages;
- if(loadedimages == totalimages){
- //全部圖片加載完成時…..
- }
- });
雙擊不選中文本
- var clearSelection = function () {
- if(document.selection && document.selection.empty) {
- document.selection.empty();
- } else if(window.getSelection) {
- var sel = window.getSelection();
- sel.removeAllRanges();
- }
- }
- $(element).bind(‘dblclick’,function(event){
- clearSelection();
- });
對一個列表進行排序
- <ul>
- <li>cloud</li>
- <li>sun</li>
- <li>rain</li>
- <li>snow</li>
- </ul
- var items = $(‘.to_order li’).get();
- items.sort(function(a,b){
- var keyA = $(a).text();
- var keyB = $(b).text();
- if (keyA < keyB) return -1;
- if (keyA > keyB) return 1;
- return 0;
- });
- var ul = $(‘.to_order’);
- $.each(items, function(i, li){
- ul.append(li);
- });
(中文無效)
綁定右擊事件
- $(document).ready(function(){
- $(document).bind(“contextmenu”,function(e){
- return false;
- });
- });
擴展jquery的對象選擇器
- $.extend($.expr[':'], {
- //選擇器名
- moreThanAThousand : function (a){
- return parseInt($(a).html()) > 1000;
- }
- });
- $(document).ready(function() {
- $(‘td:moreThanAThousand’).css(‘background-color’, ‘#ff0000′);
- });
檢查對象是否存在
- if ($(“#elementid”).length) {
- //……
- }
取消一個ajax請求
- var req = $.ajax({
- type: “POST”,
- url: “someurl”,
- data: “id=1″,
- success: function(){
- }
- });
- //取消ajax請求
- req.abort()
檢查cookies是否可用
- $(document).ready(function() {
- var dt = new Date();
- dt.setSeconds(dt.getSeconds() + 60);
- document.cookie = “cookietest=1; expires=” + dt.toGMTString();
- var cookiesEnabled = document.cookie.indexOf(“cookietest=”) != -1;
- if(!cookiesEnabled){
- //cookies不能用……..
- }
- });
獲取當前元素在元素集內的索引值
- $(“ul > li”).click(function () {
- var index = $(this).prevAll().length;
- });
如果你用的是jquery1.4,明河推薦使用以下方法:
- $(“ul > li”).click(function () {
- var index = $(this).index();
- });
讓一個元素相對于屏幕居中
- jQuery.fn.center = function () {
- this.css(“position”,”absolute”);
- this.css(“top”, ( $(window).height() – this.height() ) / 2+$(window).scrollTop() + “px”);
- this.css(“left”, ( $(window).width() – this.width() ) / 2+$(window).scrollLeft() + “px”);
- return this;
- }
- $(element).center();
這個方法非常實用,明河嚴重推薦收藏
獲取當前頁面的URL
- $(document).ready(function() {
- var pathname = window.location.pathname;
- });
如何隱藏除了特定選擇器下的全部對象
- $(‘#target div:not(#exclude)’).hide();
- //或者
- $(‘#target’).children().filter(‘:not(#exclude)’).hide();
filter()起到過濾的作用。
尋找帶有指定字符串的元素
- var foundin = $(‘*:contains(” 明河”)’);
獲取垂直滾動距離
- alert($(document).scrollTop());
scrollTop()非常實用的一個方法。
向表格追加一行數據
- $(‘#myTable tr:last’).after(‘<tr>…</tr>’);
超過一個屬性時的過濾
- var elements = $(‘#someid input[type=sometype][value=somevalue]‘).get();
讓cookies在X分鐘后過期
- var date = new Date();
- date.setTime(date.getTime() + (x * 60 * 1000));
- $.cookie(‘example’, ‘foo’, { expires: date });
選擇從第一個到第X個的元素
- //從第一個到第10個
- $(‘a’).slice(0,10);
- //或者
- $(‘a:lt(10)’);
獲取客戶端的IP
- $.getJSON(“http://jsonip.appspot.com?callback=?”,function(data){
- alert( “你的IP:” + data.ip);
- });
這是利用了jsonip.appspot.com提供的取IP服務。
解析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>
- $.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 …
- });
- });
獲取在id中的數字
- <div id=”sites”>
- <a id=”site_1″ href=”http://siteA.com”>siteA</a>
- <a id=”site_2″ href=”http://siteB.com”>siteB</a>
- <a id=”site_3″ href=”http://siteB.com”>siteC</a>
- …
- </div>
- $(“#sites a”).click(function(){
- var $this = $(this);
- var nmb = $this.attr(‘id’).match(/site_(\d+)/)[1];
- …
- });
將類似12343778 轉成 12.343.778的形式
- var delimiter = ‘.’;
- $(‘#result’).html()
- .toString()
- .replace(new RegExp(“(^\\d{“+($this.html().toString().length%3||-1)+”})(?=\\d{3})”),”$1″ + delimiter)
- .replace(/(\d{3})(?=\d)/g,”$1″ + delimiter);
這個正則值得收藏,頗為經典。
向firebug的控制面板發送消息
- jQuery.fn.log = function (msg) {
- console.log(“%s: %o”, msg, this);
- return this;
- };
- $(‘#some_div’).find(‘li.source > input:checkbox’).log(“sources to uncheck”).removeAttr(“checked”);
獲取圖片的寬高
- var img = $(‘#imageid’);
- var theImage = new Image();
- theImage.src = img.attr(“src”);
- alert(“Width: ” + theImage.width);
- alert(“Height: ” + theImage.height);
本文由用戶 umltool 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!