10个PHP代码片段

还记得CSDN研发频道此前发表过的一篇《可以直接拿来用的15个jQuery代码片段》吗?本文笔者将继续为你奉上10个超级有用的PHP代码片段。

PHP是一种HTML内嵌式的语言,是一种在服务器端执行的嵌入HTML文档的脚本语言。PHP拥有数以百计的基本功能,支持上千种扩展。这些功能都被很好的加载在PHP站点上,但内置的库有各种各样的命名。在PHP代码库中包含了无数个有用的PHP代码片段,每位开发者都需要不断完善自己的“工具箱”。有了这些代码片段可以为你节省大量的时间,一起来看下。

1.查找Longitudes与Latitudes之间的距离

  1. function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {  
  2.     $theta = $longitude1 - $longitude2;  
  3.     $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));  
  4.     $miles = acos($miles);  
  5.     $miles = rad2deg($miles);  
  6.     $miles = $miles * 60 * 1.1515;  
  7.     $feet = $miles * 5280;  
  8.     $yards = $feet / 3;  
  9.     $kilometers = $miles * 1.609344;  
  10.     $meters = $kilometers * 1000;  
  11.     return compact('miles','feet','yards','kilometers','meters');   
  12. }  
  13.   
  14. $point1 = array('lat' => 40.770623, 'long' => -73.964367);  
  15. $point2 = array('lat' => 40.758224, 'long' => -73.917404);  
  16. $distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);  
  17. foreach ($distance as $unit => $value) {  
  18.     echo $unit.': '.number_format($value,4).'  
  19. ';  
  20. }  
  21.   
  22. The example returns the following:  
  23.   
  24. miles: 2.6025  
  25. feet: 13,741.4350  
  26. yards: 4,580.4783  
  27. kilometers: 4.1884  
  28. meters: 4,188.3894  

源码

2.完善cURL功能

  1. function xcurl($url,$ref=null,$post=array(),$ua="Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre",$print=false) {  
  2.     $ch = curl_init();  
  3.     curl_setopt($ch, CURLOPT_AUTOREFERER, true);  
  4.     if(!empty($ref)) {  
  5.         curl_setopt($ch, CURLOPT_REFERER, $ref);  
  6.     }  
  7.     curl_setopt($ch, CURLOPT_URL, $url);  
  8.     curl_setopt($ch, CURLOPT_HEADER, 0);  
  9.     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
  10.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
  11.     if(!empty($ua)) {  
  12.         curl_setopt($ch, CURLOPT_USERAGENT, $ua);  
  13.     }  
  14.     if(count($post) > 0){  
  15.         curl_setopt($ch, CURLOPT_POST, 1);  
  16.         curl_setopt($ch, CURLOPT_POSTFIELDS, $post);      
  17.     }  
  18.     $output = curl_exec($ch);  
  19.     curl_close($ch);  
  20.     if($print) {  
  21.         print($output);  
  22.     } else {  
  23.         return $output;  
  24.     }  
  25. }  

源码

3.清理用户输入

  1. ]*?>.*?@si',   // Strip out javascript  
  2.     '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags  
  3.     '@]*?>.*?@siU',    // Strip style tags properly  
  4.     '@@'         // Strip multi-line comments  
  5.   );  
  6.   
  7.     $output = preg_replace($search, '', $input);  
  8.     return $output;  
  9.   }  
  10. ?>  
  11. $val) {  
  12.             $output[$var] = sanitize($val);  
  13.         }  
  14.     }  
  15.     else {  
  16.         if (get_magic_quotes_gpc()) {  
  17.             $input = stripslashes($input);  
  18.         }  
  19.         $input  = cleanInput($input);  
  20.         $output = mysql_real_escape_string($input);  
  21.     }  
  22.     return $output;  
  23. }  
  24. ?>  

源码

4.通过IP(城市、国家)检测地理位置

  1. function detect_city($ip) {  
  2.   
  3.         $default = 'Hollywood, CA';  
  4.   
  5.         if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')             $ip = '8.8.8.8';           $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';           $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);         $ch = curl_init();           $curl_opt = array(             CURLOPT_FOLLOWLOCATION  => 1,  
  6.             CURLOPT_HEADER      => 0,  
  7.             CURLOPT_RETURNTRANSFER  => 1,  
  8.             CURLOPT_USERAGENT   => $curlopt_useragent,  
  9.             CURLOPT_URL       => $url,  
  10.             CURLOPT_TIMEOUT         => 1,  
  11.             CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],  
  12.         );  
  13.   
  14.         curl_setopt_array($ch, $curl_opt);  
  15.   
  16.         $content = curl_exec($ch);  
  17.   
  18.         if (!is_null($curl_info)) {  
  19.             $curl_info = curl_getinfo($ch);  
  20.         }  
  21.   
  22.         curl_close($ch);  
  23.   
  24.         if ( preg_match('{  
  25.   
  26.       
  27. City : ([^<]*)  
  28. }i', $content, $regs) ) { $city = $regs[1]; } if ( preg_match('{  
  29.       
  30. State/Province : ([^<]*)  
  31.   
  32. }i', $content, $regs) ) { $state = $regs[1]; } if( $city!='' && $state!='' ){ $location = $city . ', ' . $state; return $location; }elsereturn $default; } }  

源码

5.设置密码强度

  1.  100){   
  2.         $strength = 100;   
  3.     }   
  4.     return $strength;   
  5. }   
  6.   
  7. var_dump(password_strength("Correct Horse Battery Staple"));   
  8. echo "  
  9. ";   
  10. var_dump(password_strength("Super Monkey Ball"));   
  11. echo "  
  12. ";   
  13. var_dump(password_strength("Tr0ub4dor&3"));   
  14. echo "  
  15. ";   
  16. var_dump(password_strength("abc123"));   
  17. echo "  
  18. ";   
  19. var_dump(password_strength("sweet"));  

源码

6.检测浏览器语言,只提供可用的$availableLanguages作为数组(‘en’, ‘de’, ‘es’)

 

  1. function get_client_language($availableLanguages, $default='en'){  
  2.       
  3.     if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {  
  4.               
  5.         $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);  
  6.   
  7.         //start going through each one  
  8.         foreach ($langs as $value){  
  9.       
  10.             $choice=substr($value,0,2);  
  11.             if(in_array($choice, $availableLanguages)){  
  12.                 return $choice;  
  13.                   
  14.             }  
  15.               
  16.         }  
  17.     }   
  18.     return $default;  
  19. }  

源码

7.创建数据URL

  1. function data_uri($file, $mime) {  
  2.   $contents=file_get_contents($file);  
  3.   $base64=base64_encode($contents);  
  4.   echo "data:$mime;base64,$base64";  
  5. }  

源码

8.创建更加友好的页面标题SEO URL

输入示例:$title = “This foo’s bar is rockin’ cool!”; echo makeseoname($title); //RETURNS: //this-foos-bar-is-rockin-cool

  1. function make_seo_name($title) {  
  2.     return preg_replace('/[^a-z0-9_-]/i''', strtolower(str_replace(' ''-', trim($title))));  
  3. }  

源码

9.终极加密功能

  1. // f(ucking) u(ncrackable) e(ncryption) function by BlackHatDBL (www.netforme.net)  
  2. function fue($hash,$times) {  
  3.     // Execute the encryption(s) as many times as the user wants  
  4.     for($i=$times;$i>0;$i--) {  
  5.         // Encode with base64...  
  6.         $hash=base64_encode($hash);  
  7.         // and md5...  
  8.         $hash=md5($hash);  
  9.         // sha1...  
  10.         $hash=sha1($hash);  
  11.         // sha256... (one more)  
  12.         $hash=hash("sha256", $hash);  
  13.         // sha512  
  14.         $hash=hash("sha512", $hash);  
  15.   
  16.     }  
  17.     // Finaly, when done, return the value  
  18.     return $hash;  
  19. }  

源码

10a.Tweeter Feed Runner——使用任意twitter名,可在任意页面上加载用户资源。

 

  1. pversion;   
  2.     }   
  3.     public function loadTimeline($user, $max = 20){   
  4.         $this->twitURL .= 'statuses/user_timeline.xml?screen_name='.$user.'&count='.$max;   
  5.         $ch        = curl_init();   
  6.         curl_setopt($ch, CURLOPT_URL, $this->twitURL);   
  7.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   
  8.         $this->xml = curl_exec($ch);   
  9.         return $this;   
  10.     }   
  11.     public function getTweets(){   
  12.         $this->twitterArr = $this->getTimelineArray();   
  13.         $tweets = array();   
  14.         foreach($this->twitterArr->status as $status){   
  15.             $tweets[$status->created_at->__toString()] = $status->text->__toString();   
  16.         }   
  17.         return $tweets;   
  18.     }   
  19.     public function getTimelineArray(){   
  20.         return simplexml_load_string($this->xml);   
  21.     }   
  22.     public function formatTweet($tweet){   
  23.         $tweet = preg_replace("/(http(.+?))( |$)/","$1$3", $tweet);   
  24.         $tweet = preg_replace("/#(.+?)(\h|\W|$)/""#$1$2", $tweet);   
  25.         $tweet = preg_replace("/@(.+?)(\h|\W|$)/""@$1$2", $tweet);   
  26.         return $tweet;   
  27.     }   
  28. }  

10b. Tweeter Feed Runner——用于在主题中创建文件,比如:example.php

 

  1. loadTimeline("phpsnips")->getTweets();   
  2. foreach($feed as $time => $message){   
  3.     echo "<div class='tweet'>".$twitter->formatTweet($message)."<br />At: ".$time."</div>";   
  4. }  

源码

 

每位程序员和开发者都喜欢讨论他们最爱的代码片段,尤其是当PHP开发者花费数个小时为网页编码或创建应用时,他们更知道这些代码的重要性。为了节约编码时间,笔者收集了一些较为实用的代码片段,帮助开发者提高工作效率。>>> 点击查看PHP代码片段(一)

1) Whois query using PHP ——利用PHP获取Whois请求 

利用这段代码,在特定的域名里可获得whois信息。把域名名称作为参数,并显示所有域名的相关信息。

  1. function whois_query($domain) {  
  2.   
  3.     // fix the domain name:  
  4.     $domain = strtolower(trim($domain));  
  5.     $domain = preg_replace('/^http:\/\//i''', $domain);  
  6.     $domain = preg_replace('/^www\./i''', $domain);  
  7.     $domain = explode('/', $domain);  
  8.     $domain = trim($domain[0]);  
  9.   
  10.     // split the TLD from domain name  
  11.     $_domain = explode('.', $domain);  
  12.     $lst = count($_domain)-1;  
  13.     $ext = $_domain[$lst];  
  14.   
  15.     // You find resources and lists   
  16.     // like these on wikipedia:   
  17.     //  
  18.     // <a href="http://de.wikipedia.org/wiki/Whois">http://de.wikipedia.org/wiki/Whois</a>  
  19.     //  
  20.     $servers = array(  
  21.         "biz" => "whois.neulevel.biz",  
  22.         "com" => "whois.internic.net",  
  23.         "us" => "whois.nic.us",  
  24.         "coop" => "whois.nic.coop",  
  25.         "info" => "whois.nic.info",  
  26.         "name" => "whois.nic.name",  
  27.         "net" => "whois.internic.net",  
  28.         "gov" => "whois.nic.gov",  
  29.         "edu" => "whois.internic.net",  
  30.         "mil" => "rs.internic.net",  
  31.         "int" => "whois.iana.org",  
  32.         "ac" => "whois.nic.ac",  
  33.         "ae" => "whois.uaenic.ae",  
  34.         "at" => "whois.ripe.net",  
  35.         "au" => "whois.aunic.net",  
  36.         "be" => "whois.dns.be",  
  37.         "bg" => "whois.ripe.net",  
  38.         "br" => "whois.registro.br",  
  39.         "bz" => "whois.belizenic.bz",  
  40.         "ca" => "whois.cira.ca",  
  41.         "cc" => "whois.nic.cc",  
  42.         "ch" => "whois.nic.ch",  
  43.         "cl" => "whois.nic.cl",  
  44.         "cn" => "whois.cnnic.net.cn",  
  45.         "cz" => "whois.nic.cz",  
  46.         "de" => "whois.nic.de",  
  47.         "fr" => "whois.nic.fr",  
  48.         "hu" => "whois.nic.hu",  
  49.         "ie" => "whois.domainregistry.ie",  
  50.         "il" => "whois.isoc.org.il",  
  51.         "in" => "whois.ncst.ernet.in",  
  52.         "ir" => "whois.nic.ir",  
  53.         "mc" => "whois.ripe.net",  
  54.         "to" => "whois.tonic.to",  
  55.         "tv" => "whois.tv",  
  56.         "ru" => "whois.ripn.net",  
  57.         "org" => "whois.pir.org",  
  58.         "aero" => "whois.information.aero",  
  59.         "nl" => "whois.domain-registry.nl"  
  60.     );  
  61.   
  62.     if (!isset($servers[$ext])){  
  63.         die('Error: No matching nic server found!');  
  64.     }  
  65.   
  66.     $nic_server = $servers[$ext];  
  67.   
  68.     $output = '';  
  69.   
  70.     // connect to whois server:  
  71.     if ($conn = fsockopen ($nic_server, 43)) {  
  72.         fputs($conn, $domain."\r\n");  
  73.         while(!feof($conn)) {  
  74.             $output .= fgets($conn,128);  
  75.         }  
  76.         fclose($conn);  
  77.     }  
  78.     else { die('Error: Could not connect to ' . $nic_server . '!'); }  
  79.   
  80.     return $output;  
  81. }  

2) Text messaging with PHP using the TextMagic API ——使用TextMagic API 获取PHP Test信息

TextMagic引入强大的核心API,可轻松将SMS发送到手机。该API是需要付费。

  1. the TextMagic PHP lib  
  2. require('textmagic-sms-api-php/TextMagicAPI.php');  
  3.   
  4. // Set the username and password information  
  5. $username = 'myusername';  
  6. $password = 'mypassword';  
  7.   
  8. // Create a new instance of TM  
  9. $router = new TextMagicAPI(array(  
  10.     'username' => $username,  
  11.     'password' => $password  
  12. ));  
  13.   
  14. // Send a text message to '999-123-4567'  
  15. $result = $router->send('Wake up!', array(9991234567), true);  
  16.   
  17. // result:  Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )  

3) Get info about your memory usage——获取内存使用率

这段代码帮助你获取内存使用率。

  1. echo "Initial: ".memory_get_usage()." bytes \n";  
  2. /* prints 
  3. Initial: 361400 bytes 
  4. */  
  5.   
  6. // let's use up some memory  
  7. for ($i = 0; $i < 100000; $i++) {  
  8.     $array []= md5($i);  
  9. }  
  10.   
  11. // let's remove half of the array  
  12. for ($i = 0; $i < 100000; $i++) {  
  13.     unset($array[$i]);  
  14. }  
  15.   
  16. echo "Final: ".memory_get_usage()." bytes \n";  
  17. /* prints 
  18. Final: 885912 bytes 
  19. */  
  20.   
  21. echo "Peak: ".memory_get_peak_usage()." bytes \n";  
  22. /* prints 
  23. Peak: 13687072 bytes 
  24. */  

4) Display source code of any webpage——查看任意网页源代码

如果你想查看网页源代码,那么只需更改第二行的URL,源代码就会在网页上显示出。

  1. <?php // display source code $lines = file('http://google.com/'); foreach ($lines as $line_num => $line) {   
  2.     // loop thru each line and prepend line numbers  
  3.     echo "Line #{$line_num} : " . htmlspecialchars($line) . "  
  4. \n";  
  5. }  

5) Create data uri’s——创建数据uri

通过使用此代码,你可以创建数据Uri,这对在HTML/CSS中嵌入图片非常有用,可帮助节省HTTP请求。

  1. function data_uri($file, $mime) {  
  2.   $contents=file_get_contents($file);  
  3.   $base64=base64_encode($contents);  
  4.   echo "data:$mime;base64,$base64";  
  5. }  

6) Detect location by IP——通过IP检索出地理位置

这段代码帮助你查找特定的IP,只需在功能参数上输入IP,就可检测出位置。

  1. function detect_city($ip) {  
  2.   
  3.         $default = 'UNKNOWN';  
  4.   
  5.         if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')             $ip = '8.8.8.8';         $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';                  $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);         $ch = curl_init();                  $curl_opt = array(             CURLOPT_FOLLOWLOCATION  => 1,  
  6.             CURLOPT_HEADER      => 0,  
  7.             CURLOPT_RETURNTRANSFER  => 1,  
  8.             CURLOPT_USERAGENT   => $curlopt_useragent,  
  9.             CURLOPT_URL       => $url,  
  10.             CURLOPT_TIMEOUT         => 1,  
  11.             CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],  
  12.         );  
  13.   
  14.         curl_setopt_array($ch, $curl_opt);  
  15.   
  16.         $content = curl_exec($ch);  
  17.   
  18.         if (!is_null($curl_info)) {  
  19.             $curl_info = curl_getinfo($ch);  
  20.         }  
  21.   
  22.         curl_close($ch);  
  23.   
  24.         if ( preg_match('{  
  25. City : ([^<]*)  
  26. }i’, $content, $regs) ) { $city = $regs[1]; } if ( preg_match(‘{  
  27.   
  28. State/Province : ([^<]*)  
  29.    
  30. }i’, $content, $regs) ) { $state = $regs[1]; } if( $city!=” && $state!=” ){ $location = $city . ‘, ‘ . $state; return $location; }elsereturn $default; } }  

7) Detect browser language——查看浏览器语言

检测浏览器使用的代码脚本语言。

  1. function get_client_language($availableLanguages, $default='en'){  
  2.     if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {  
  3.         $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);  
  4.   
  5.         foreach ($langs as $value){  
  6.             $choice=substr($value,0,2);  
  7.             if(in_array($choice, $availableLanguages)){  
  8.                 return $choice;  
  9.             }  
  10.         }  
  11.     }   
  12.     return $default;  
  13. }  

8) Check if server is HTTPS——检测服务器是否是HTTPS

  1. if ($_SERVER['HTTPS'] != "on") {   
  2.     echo "This is not HTTPS";  
  3. }else{  
  4.     echo "This is HTTPS";  
  5. }  

9) Generate CSV file from a PHP array——在PHP数组中生成.csv 文件

    1. function generateCsv($data, $delimiter = ',', $enclosure = '"') {  
    2.    $handle = fopen('php://temp''r+');  
    3.    foreach ($data as $line) {  
    4.            fputcsv($handle, $line, $delimiter, $enclosure);  
    5.    }  
    6.    rewind($handle);  
    7.    while (!feof($handle)) {  
    8.            $contents .= fread($handle, 8192);  
    9.    }  
    10.    fclose($handle);  
    11.    return $contents;  

 

 

jQuery里提供了许多创建交互式网站的方法,在开发Web项目时,开发人员应该好好利用jQuery代码,它们不仅能给网站带来各种动画、特效,还会提高网站的用户体验。

本文收集了15段非常实用的jQuery代码片段,你可以直接复制黏贴到代码里,但请开发者注意了,要理解代码再使用哦。下面就让我们一起来享受jQuery代码的魅力之处吧。

1.预加载图片

  1. (function($) {  
  2.   var cache = [];  
  3.   // Arguments are image paths relative to the current page.  
  4.   $.preLoadImages = function() {  
  5.     var args_len = arguments.length;  
  6.     for (var i = args_len; i--;) {  
  7.       var cacheImage = document.createElement('img');  
  8.       cacheImage.src = arguments[i];  
  9.       cache.push(cacheImage);  
  10.     }  
  11.   }  
  12. jQuery.preLoadImages("image1.gif""/path/to/image2.png");  

源码

2. 让页面中的每个元素都适合在移动设备上展示

  1. var scr = document.createElement('script');  
  2. scr.setAttribute('src''https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js');  
  3. document.body.appendChild(scr);  
  4. scr.onload = function(){  
  5.     $('div').attr('class''').attr('id''').css({  
  6.         'margin' : 0,  
  7.         'padding' : 0,  
  8.         'width''100%',  
  9.         'clear':'both'  
  10.     });  
  11. };  

源码

3.图像等比例缩放

  1. $(window).bind("load"function() {  
  2.     // IMAGE RESIZE  
  3.     $('#product_cat_list img').each(function() {  
  4.         var maxWidth = 120;  
  5.         var maxHeight = 120;  
  6.         var ratio = 0;  
  7.         var width = $(this).width();  
  8.         var height = $(this).height();  
  9.         if(width > maxWidth){  
  10.             ratio = maxWidth / width;  
  11.             $(this).css("width", maxWidth);  
  12.             $(this).css("height", height * ratio);  
  13.             height = height * ratio;  
  14.         }  
  15.         var width = $(this).width();  
  16.         var height = $(this).height();  
  17.         if(height > maxHeight){  
  18.             ratio = maxHeight / height;  
  19.             $(this).css("height", maxHeight);  
  20.             $(this).css("width", width * ratio);  
  21.             width = width * ratio;  
  22.         }  
  23.     });  
  24.     //$("#contentpage img").show();  
  25.     // IMAGE RESIZE  
  26. });  

源码

4.返回页面顶部

  1. // Back To Top  
  2. $(document).ready(function(){   
  3.   $('.top').click(function() {    
  4.      $(document).scrollTo(0,500);    
  5.   });  
  6. });   
  7. //Create a link defined with the class .top  
  8. <a href="#" class="top">Back To Top</a>  

源码

5.使用jQuery打造手风琴式的折叠效果

  1. var accordion = {  
  2.      init: function(){  
  3.            var $container = $('#accordion');  
  4.            $container.find('li:not(:first) .details').hide();  
  5.            $container.find('li:first').addClass('active');  
  6.            $container.on('click','li a',function(e){  
  7.                   e.preventDefault();  
  8.                   var $this = $(this).parents('li');  
  9.                   if($this.hasClass('active')){  
  10.                          if($('.details').is(':visible')) {  
  11.                                 $this.find('.details').slideUp();  
  12.                          } else {  
  13.                                 $this.find('.details').slideDown();  
  14.                          }  
  15.                   } else {  
  16.                          $container.find('li.active .details').slideUp();  
  17.                          $container.find('li').removeClass('active');  
  18.                          $this.addClass('active');  
  19.                          $this.find('.details').slideDown();  
  20.                   }  
  21.            });  
  22.      }  
  23. };  

6.通过预加载图片廊中的上一幅下一幅图片来模仿Facebook的图片展示方式

  1. var nextimage = "/images/some-image.jpg";  
  2. $(document).ready(function(){  
  3. window.setTimeout(function(){  
  4. var img = $("").attr("src", nextimage).load(function(){  
  5. //all done  
  6. });  
  7. }, 100);  
  8. });  

源码

7.使用jQuery和Ajax自动填充选择框

  1. $(function(){  
  2. $("select#ctlJob").change(function(){  
  3. $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){  
  4. var options = '';  
  5. for (var i = 0; i < j.length; i++) {  
  6. options += '  
  7. ' + j[i].optionDisplay + '  
  8. ';  
  9. }  
  10. $("select#ctlPerson").html(options);  
  11. })  
  12. })  
  13. })  

源码

8.自动替换丢失的图片

  1. // Safe Snippet  
  2. $("img").error(function () {  
  3.     $(this).unbind("error").attr("src""missing_image.gif");  
  4. });  
  5. // Persistent Snipper  
  6. $("img").error(function () {  
  7.     $(this).attr("src""missing_image.gif");  
  8. });  

源码

9.在鼠标悬停时显示淡入/淡出特效

  1. $(document).ready(function(){  
  2.     $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads  
  3.     $(".thumbs img").hover(function(){  
  4.         $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover  
  5.     },function(){  
  6.         $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout  
  7.     });  
  8. });  

源码

10.清空表单数据

  1. function clearForm(form) {  
  2.   // iterate over all of the inputs for the form  
  3.   // element that was passed in  
  4.   $(':input', form).each(function() {  
  5.     var type = this.type;  
  6.     var tag = this.tagName.toLowerCase(); // normalize case  
  7.     // it's ok to reset the value attr of text inputs,  
  8.     // password inputs, and textareas  
  9.     if (type == 'text' || type == 'password' || tag == 'textarea')  
  10.       this.value = "";  
  11.     // checkboxes and radios need to have their checked state cleared  
  12.     // but should *not* have their 'value' changed  
  13.     else if (type == 'checkbox' || type == 'radio')  
  14.       this.checked = false;  
  15.     // select elements need to have their 'selectedIndex' property set to -1  
  16.     // (this works for both single and multiple select elements)  
  17.     else if (tag == 'select')  
  18.       this.selectedIndex = -1;  
  19.   });  
  20. };  

源码

11.预防对表单进行多次提交

  1. $(document).ready(function() {  
  2.   $('form').submit(function() {  
  3.     if(typeof jQuery.data(this"disabledOnSubmit") == 'undefined') {  
  4.       jQuery.data(this"disabledOnSubmit", { submited: true });  
  5.       $('input[type=submit], input[type=button]'this).each(function() {  
  6.         $(this).attr("disabled""disabled");  
  7.       });  
  8.       return true;  
  9.     }  
  10.     else  
  11.     {  
  12.       return false;  
  13.     }  
  14.   });  
  15. });  

源码

12.动态添加表单元素

  1. //change event on password1 field to prompt new input  
  2. $('#password1').change(function() {  
  3.         //dynamically create new input and insert after password1  
  4.         $("#password1").append("");  
  5. });  

源码

13.让整个Div可点击

  1. blah blah blah. link  
  2. The following lines of jQuery will make the entire div clickable: $(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false; });   

源码

14.平衡高度或Div元素

  1. var maxHeight = 0;  
  2. $("div").each(function(){  
  3.    if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }  
  4. });  
  5. $("div").height(maxHeight);  

源码

15. 在窗口滚动时自动加载内容

    1. var loading = false;  
    2. $(window).scroll(function(){  
    3.     if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){  
    4.         if(loading == false){  
    5.             loading = true;  
    6.             $('#loadingbar').css("display","block");  
    7.             $.get("load.php?start="+$('#loaded_max').val(), function(loaded){  
    8.                 $('body').append(loaded);  
    9.                 $('#loaded_max').val(parseInt($('#loaded_max').val())+50);  
    10.                 $('#loadingbar').css("display","none");  
    11.                 loading = false;  
    12.             });  
    13.         }  
    14.     }  
    15. });  
    16. $(document).ready(function() {  
    17.     $('#loaded_max').val(50);  
    18. }); 

posted on 2014-03-18 12:02  蓝海旗舰  阅读(225)  评论(0编辑  收藏  举报

导航