还记得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. $point1 = array('lat' => 40.770623, 'long' => -73.964367);
  14. $point2 = array('lat' => 40.758224, 'long' => -73.917404);
  15. $distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
  16. foreach ($distance as $unit => $value) {
  17. echo $unit.': '.number_format($value,4).'
  18. ';
  19. }
  20. The example returns the following:
  21. miles: 2.6025
  22. feet: 13,741.4350
  23. yards: 4,580.4783
  24. kilometers: 4.1884
  25. 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. $output = preg_replace($search, '', $input);
  7. return $output;
  8. }
  9. ?>
  10. $val) {
  11. $output[$var] = sanitize($val);
  12. }
  13. }
  14. else {
  15. if (get_magic_quotes_gpc()) {
  16. $input = stripslashes($input);
  17. }
  18. $input  = cleanInput($input);
  19. $output = mysql_real_escape_string($input);
  20. }
  21. return $output;
  22. }
  23. ?>

源码

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

  1. function detect_city($ip) {
  2. $default = 'Hollywood, CA';
  3. 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,
  4. CURLOPT_HEADER      => 0,
  5. CURLOPT_RETURNTRANSFER  => 1,
  6. CURLOPT_USERAGENT   => $curlopt_useragent,
  7. CURLOPT_URL       => $url,
  8. CURLOPT_TIMEOUT         => 1,
  9. CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
  10. );
  11. curl_setopt_array($ch, $curl_opt);
  12. $content = curl_exec($ch);
  13. if (!is_null($curl_info)) {
  14. $curl_info = curl_getinfo($ch);
  15. }
  16. curl_close($ch);
  17. if ( preg_match('{
  18. City : ([^<]*)
  19. }i', $content, $regs) ) { $city = $regs[1]; } if ( preg_match('{
  20. State/Province : ([^<]*)
  21. }i', $content, $regs) ) { $state = $regs[1]; } if( $city!='' && $state!='' ){ $location = $city . ', ' . $state; return $location; }else{ return $default; } }

源码

5.设置密码强度

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

源码

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

  1. function get_client_language($availableLanguages, $default='en'){
  2. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  3. $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
  4. //start going through each one
  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. }

源码

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. // Finaly, when done, return the value
  17. return $hash;
  18. }

源码

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

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. // Set the username and password information
  4. $username = 'myusername';
  5. $password = 'mypassword';
  6. // Create a new instance of TM
  7. $router = new TextMagicAPI(array(
  8. 'username' => $username,
  9. 'password' => $password
  10. ));
  11. // Send a text message to '999-123-4567'
  12. $result = $router->send('Wake up!', array(9991234567), true);
  13. // 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. // let's use up some memory
  6. for ($i = 0; $i < 100000; $i++) {
  7. $array []= md5($i);
  8. }
  9. // let's remove half of the array
  10. for ($i = 0; $i < 100000; $i++) {
  11. unset($array[$i]);
  12. }
  13. echo "Final: ".memory_get_usage()." bytes \n";
  14. /* prints
  15. Final: 885912 bytes
  16. */
  17. echo "Peak: ".memory_get_peak_usage()." bytes \n";
  18. /* prints
  19. Peak: 13687072 bytes
  20. */

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. $default = 'UNKNOWN';
  3. 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,
  4. CURLOPT_HEADER      => 0,
  5. CURLOPT_RETURNTRANSFER  => 1,
  6. CURLOPT_USERAGENT   => $curlopt_useragent,
  7. CURLOPT_URL       => $url,
  8. CURLOPT_TIMEOUT         => 1,
  9. CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
  10. );
  11. curl_setopt_array($ch, $curl_opt);
  12. $content = curl_exec($ch);
  13. if (!is_null($curl_info)) {
  14. $curl_info = curl_getinfo($ch);
  15. }
  16. curl_close($ch);
  17. if ( preg_match('{
  18. City : ([^<]*)
  19. }i’, $content, $regs) ) { $city = $regs[1]; } if ( preg_match(‘{
  20. State/Province : ([^<]*)
  21. }i’, $content, $regs) ) { $state = $regs[1]; } if( $city!=” && $state!=” ){ $location = $city . ‘, ‘ . $state; return $location; }else{ return $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. foreach ($langs as $value){
  5. $choice=substr($value,0,2);
  6. if(in_array($choice, $availableLanguages)){
  7. return $choice;
  8. }
  9. }
  10. }
  11. return $default;
  12. }

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;
    12. }

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. });

最新文章

  1. 面试题目——《CC150》线程与锁
  2. 1013. Battle Over Cities
  3. csshover.htc CSS兼容
  4. Qt Write and Read XML File 读写XML文件
  5. Linux:挂载外部U盘,移动数据
  6. windbg
  7. const,static,extern简介(重要)
  8. WebForm上传文件FileUpload
  9. CentOS6下yum下载的包存放路径
  10. 剑指Offer:面试题13——在O(1)时间删除链表结点
  11. android sudio 记录
  12. ODPS 下一个map / reduce 准备
  13. POJ 1631 Bridging signals(LIS 二分法 高速方法)
  14. 【hoj】2651 pie 二分查找
  15. W3Cschool学习笔记&mdash;&mdash;XHTML基础教程
  16. HDOJ 1507 Uncle Tom&amp;#39;s Inherited Land*
  17. input驱动12种事件类型Event types的含义
  18. 《MySQL必知必会》整理
  19. 20165303魏煜第一周kali安装
  20. Runable和Thread

热门文章

  1. HDU1251 统计难题(字典树|map
  2. centos 7 源码安装 mysql 5.6
  3. CSP前模板复习
  4. 在Powershell中使用Group-Object和-GroupBy
  5. RBAC(基于角色的访问控制)用户权限管理数据库设计
  6. shell脚本中的数组
  7. shell cat EOF 变量自动解析问题
  8. zk和eureka的区别(CAP原则)
  9. PAT Basic 1014 福尔摩斯的约会 (20 分)
  10. The Multilinear Structure of ReLU Networks