實用jquery代碼片段集合

umltool 15年前發布 | 2K 次閱讀

加載google的jquery

  1. <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>

有利于加快加載速度(已經得到驗證)。

修改圖片src更新圖片
  1. $(imageobj).attr(‘src’, $(imageobj).attr(‘src’) + ‘?’ + Math.random() );


(這是很實用的技巧,曾經有人問明河,為什么他已經修改了圖片的src,但圖片沒變化呢?原因在于緩存,給圖片路徑后加個隨機數參數即可。

加載多張圖片,判斷加載完成狀態
  1. var totalimages = 10;
  2. var loadedimages = 0;
  3. $(“<img/>”).load(function() {
  4. ++loadedimages;
  5. if(loadedimages == totalimages){
  6. //全部圖片加載完成時…..
  7. }
  8. });
雙擊不選中文本
  1. var clearSelection = function () {
  2. if(document.selection && document.selection.empty) {
  3. document.selection.empty();
  4. } else if(window.getSelection) {
  5. var sel = window.getSelection();
  6. sel.removeAllRanges();
  7. }
  8. }

  9. $(element).bind(‘dblclick’,function(event){
  10. clearSelection();
  11. });
對一個列表進行排序
  1. <ul>
  2. <li>cloud</li>
  3. <li>sun</li>
  4. <li>rain</li>
  5. <li>snow</li>
  6. </ul
  1. var items = $(‘.to_order li’).get();

  2. items.sort(function(a,b){
  3. var keyA = $(a).text();
  4. var keyB = $(b).text();
  5. if (keyA < keyB) return -1;
  6. if (keyA > keyB) return 1;
  7. return 0;
  8. });
  9. var ul = $(‘.to_order’);
  10. $.each(items, function(i, li){
  11. ul.append(li);
  12. });

(中文無效)

綁定右擊事件
  1. $(document).ready(function(){
  2. $(document).bind(“contextmenu”,function(e){
  3. return false;
  4. });
  5. });
擴展jquery的對象選擇器
  1. $.extend($.expr[':'], {
  2. //選擇器名
  3. moreThanAThousand : function (a){
  4. return parseInt($(a).html()) > 1000;
  5. }
  6. });
  7. $(document).ready(function() {
  8. $(‘td:moreThanAThousand’).css(‘background-color’, ‘#ff0000′);
  9. });
檢查對象是否存在
  1. if ($(“#elementid”).length) {
  2. //……
  3. }
取消一個ajax請求
  1. var req = $.ajax({
  2. type: “POST”,
  3. url: “someurl”,
  4. data: “id=1″,
  5. success: function(){

  6. }
  7. });
  8. //取消ajax請求
  9. req.abort()
檢查cookies是否可用
  1. $(document).ready(function() {
  2. var dt = new Date();
  3. dt.setSeconds(dt.getSeconds() + 60);
  4. document.cookie = “cookietest=1; expires=” + dt.toGMTString();
  5. var cookiesEnabled = document.cookie.indexOf(“cookietest=”) != -1;
  6. if(!cookiesEnabled){
  7. //cookies不能用……..
  8. }
  9. });
獲取當前元素在元素集內的索引值
  1. $(“ul > li”).click(function () {
  2. var index = $(this).prevAll().length;
  3. });

如果你用的是jquery1.4,明河推薦使用以下方法:

  1. $(“ul > li”).click(function () {
  2. var index = $(this).index();
  3. });
讓一個元素相對于屏幕居中
  1. jQuery.fn.center = function () {
  2. this.css(“position”,”absolute”);
  3. this.css(“top”, ( $(window).height() – this.height() ) / 2+$(window).scrollTop() + “px”);
  4. this.css(“left”, ( $(window).width() – this.width() ) / 2+$(window).scrollLeft() + “px”);
  5. return this;
  6. }
  7. $(element).center();

這個方法非常實用,明河嚴重推薦收藏

獲取當前頁面的URL
  1. $(document).ready(function() {
  2. var pathname = window.location.pathname;
  3. });
    如何隱藏除了特定選擇器下的全部對象
  4. $(‘#target div:not(#exclude)’).hide();
  5. //或者
  6. $(‘#target’).children().filter(‘:not(#exclude)’).hide();

filter()起到過濾的作用。

尋找帶有指定字符串的元素

  1. var foundin = $(‘*:contains(” 明河”)’);
獲取垂直滾動距離
  1. alert($(document).scrollTop());

scrollTop()非常實用的一個方法。

向表格追加一行數據
  1. $(‘#myTable tr:last’).after(‘<tr>…</tr>’);
超過一個屬性時的過濾
  1. var elements = $(‘#someid input[type=sometype][value=somevalue]‘).get();
讓cookies在X分鐘后過期
  1. var date = new Date();
  2. date.setTime(date.getTime() + (x * 60 * 1000));
  3. $.cookie(‘example’, ‘foo’, { expires: date });
選擇從第一個到第X個的元素
  1. //從第一個到第10個
  2. $(‘a’).slice(0,10);
  3. //或者
  4. $(‘a:lt(10)’);
獲取客戶端的IP
  1. $.getJSON(“http://jsonip.appspot.com?callback=?”,function(data){
  2. alert( “你的IP:” + data.ip);
  3. });

這是利用了jsonip.appspot.com提供的取IP服務。

解析XML數據源
  1. <?xml version=”1.0″ ?>
  2. <result>
  3. <item>
  4. <id>1</id>
  5. <title>title1</title>
  6. <description>desc1</description>
  7. </item>
  8. <item>
  9. <id>2</id>
  10. <title>title2</title>
  11. <description>desc2</description>
  12. </item>
  13. <!– … –>
  14. </result>
  1. $.get(‘file.xml’,{},function(data){
  2. $(‘item’,data).each(function(){
  3. var $this&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = $(this);
  4. var id &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;= $this.find(‘id’).text();
  5. var title &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;= $this.find(‘title’).text();
  6. var description = $this.find(‘description’).text();
  7. //do something …
  8. });
  9. });
獲取在id中的數字
  1. <div id=”sites”>
  2. <a id=”site_1″ href=”http://siteA.com”>siteA</a>
  3. <a id=”site_2″ href=”http://siteB.com”>siteB</a>
  4. <a id=”site_3″ href=”http://siteB.com”>siteC</a>
  5. </div>
  1. $(“#sites a”).click(function(){
  2. var $this &nbsp;&nbsp; &nbsp;= $(this);
  3. var nmb &nbsp;&nbsp; &nbsp;= $this.attr(‘id’).match(/site_(\d+)/)[1];
  4. });
將類似12343778 轉成 12.343.778的形式
  1. var delimiter = ‘.’;
  2. $(‘#result’).html()
  3. .toString()
  4. .replace(new RegExp(“(^\\d{“+($this.html().toString().length%3||-1)+”})(?=\\d{3})”),”$1″ + delimiter)
  5. .replace(/(\d{3})(?=\d)/g,”$1″ + delimiter);

這個正則值得收藏,頗為經典。

向firebug的控制面板發送消息
  1. jQuery.fn.log = function (msg) {
  2. console.log(“%s: %o”, msg, this);
  3. return this;
  4. };
  5. $(‘#some_div’).find(‘li.source > input:checkbox’).log(“sources to uncheck”).removeAttr(“checked”);
獲取圖片的寬高
  1. var img = $(‘#imageid’);
  2. var theImage = new Image();
  3. theImage.src = img.attr(“src”);
  4. alert(“Width: ” + theImage.width);
  5. alert(“Height: ” + theImage.height);
 本文由用戶 umltool 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!