实用jquery代码片段集合

13年前
加载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);