search
HomeWeb Front-endJS TutorialExample parsing jQuery tool function

Example parsing jQuery tool function

Dec 03, 2016 am 10:53 AM
jquery

1. $.browser object properties

Property list ​​​​​​A Mozilla Mozilla related browsers return True, otherwise False will return to True, such as Firefox

Safari Safari related browsers, otherwise returning to False, such as Safari

Opera Opera related browsers, otherwise, return to False, As Operas msie Msie related browsers return True, otherwise returning false, such as IE, 360, Sogou

Version Return to the corresponding browser version

R
$(function () {
 if ($.browser.msie) {
 alert("IE浏览器");
 }
 if ($.browser.webkit) {
 alert("webkit浏览器");
 }
 if ($.browser.mozilla) {
 alert("mozilla浏览器");
 }
 if ($.browser.safari) {
 alert("safari浏览器");
 }
 if ($.browser.opera) {
 alert("opera浏览器");
 }
 alert($.browser.version);
})
E

2. Boxmodel

return a Boolean value, if it is W3C If the box model is used, it returns true, otherwise it returns false.


  There are two types of box models, one is the W3C box model and the other is the IE box model. The fundamental difference between the two is that the W3C box model does not include padding and border, but only refers to the Height and Width of the content, while the IE box model includes padding and border.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title></title>
 <script src="jQuery.1.8.3.js" type="text/javascript"></script>
 <script type="text/javascript">
 $(function () {
  if ($.support.boxModel) {
  alert("W3C盒子模型!");
  }
  else {
  alert("IE盒子模型!");
  }
 })
 </script>
</head>
<body>
</body>
</html>

The above example pops up the W3C box model. If the top two lines are deleted, . What pops up is the IE box model.

Array and object operations


3. $.each()

This tool function can not only complete the traversal of the specified array, but also achieve the traversal of elements in the page.

Grammar: $.each(obj,fn(para1,para2)) obj is the array or object to be traversed, fn is the callback function executed for each traversed element, para1 represents the serial number of the array or the attribute of the object, and para2 represents the Properties of elements and objects.

$(function () {
  var arr = [1, 2, 3, 4, 5];
  $.each(arr, function (index, value) {
  document.write(index + ":");
  document.write(value + "<br/>");
  });
 })
    输出:
      0:1
      1:2
      2:3
      3:4
      4:5
   
   $.each()遍历数组。
$(function () {
  var arr = { "张三": "23","李四": 22,"王五": "21" };
  $.each(arr, function (index, value) {
  document.write(index + ":");
  document.write(value + "<br/>");
  });
 })
    输出:张三:23
       李四:22
       王五:21

Element traversal

<head>
 <title></title>
 <script src="jQuery.1.8.3.js" type="text/javascript"></script>
 <script type="text/javascript">
 $(function () {
  $("p").each(function () {
  $(this).css("background-color", "red");
  });
 
       //一下三行代码与以上三行效果一样
  //$.each($("p"), function () {
  // $(this).css("background-color", "red");
  //})
 })
 </script>
</head>
<body>
 <p>我是第一个P</p>
 <p>我是第二个P</p>
 <p>我是第三个P</p>
 <p>我是第四个P</p>
 <p>我是第五个P</p>
</body>
</html>


4. $.grep()

Filter elements that meet the conditions and return a new array


Syntax :$.grep(Arrar,fn(value ,index)); Pay attention to the order of the parameters of the callback function. The first one is the value, and the second one is the index.

   $.grep(Arrar,fn(value,index),[bool]); The third parameter indicates whether to invert, true means to invert, false means not to invert. If If the searched element exists in the array, the index of the searched element will be returned.

$(function () {
  var arr = [2, 5, 34, 22, 8];
  var arr1 = $.grep(arr, function(value, index) {
  return index <= 2 && value < 10;
  })
  document.write(arr1.join());  //输出2,5
 })

   $.isArray(obj)  Detect whether the parameter is an array

   $.isFunction(obj)   Detect whether the parameter is a function

   $.isEmptyObject(obj)  Detect whether the parameter is an empty object

   $.isPlainObject(obj)  Detect Whether the parameter is a pure object, that is, whether the object is created through {} or new Object() keyword.


  $.contains(container,contained) Detect whether a DOM node contains another DOM node. If yes, it returns true otherwise it means false. Note that the parameter is a DOM object, not a jQuery object.

$(function () {
  var arr = [2, 5, 34, 22, 8];
  var arr1 = $.map(arr, function (value, index) {
  if (value > 5 && index < 3) {
   return value - 10;
  }
  })
  document.write(arr.join() + "<br/>");  //2,5,34,22,8  可以看到原数组不改变
  document.write(arr1.join());        //24  新数组只获得了操作之后的结果
 })

10. $.param()


Serialized into url string

$(function () {
 var arr = [1, 2, 3, 4, 5];
 alert($.inArray(4,arr));  //弹出 3
})


11. $.makeArray()

Copy the properties of the array or array-like object to a new array (really an array) and return the new array.

$(function () {
 var str = " 你在他乡还好吗? ";
 document.write("11" + str + "11" + "<br/>");  //输出 11 你在他乡还好吗? 11
 document.write("11" + $.trim(str) + "11");   //输出 11你在他乡还好吗?11    //加个11是为了看清楚差别。
})


12. $.merge()

This function accepts two arrays or array-like objects, appends the second parameter to the first parameter, returns the first parameter, and the first The first array will be modified, but the second one will not.

$(function () {
 var arr = [1, 2, 3, 2, 1];
 document.write(jQuery.isArray(arr));  //返回true
 var str = "123";
 document.write(jQuery.isArray(str));  //返回false
})
$(function () {
 var f = fun1;
 alert($.isFunction(fun1));  //返回true
})
function fun1() { }
$(function () {
 var obj1 = {};
 var obj2 = { name: "张飞" };
 alert($.isEmptyObject(obj1));  //返回true  obj1是空对象
 alert($.isEmptyObject(obj2));  //返回false  obj2不是空对象
})
$(function () {
 var obj1 = {};
 var obj2 = { name: "张飞" };
 var obj3 = new Object();
 var obj4 = null;
 alert($.isPlainObject(obj1));  //true  通过{}创建
 alert($.isPlainObject(obj2));  //true  通过{}创建
 alert($.isPlainObject(obj3));  //true  通过new Object()创建
 alert($.isPlainObject(obj4));  //flase  不是通过{}或new Object()创建
})
$(function () {
 alert($.contains($("#div1")[0],$("#p1")[0]));  //返回true,注意参数是DOM对象,并非jQuery对象
})

13. $.parseJSON()

This function will parse the string in JSON format and return the parsing result (object). Similar to JSON.parse(), note: jQuery only defines a JSON parsing function, not a serialization function.

$(function () {
 var man = { Name: "张飞", Age: 23 };
 var str = $.param(man);
 document.write(str);      //Name=%E5%BC%A0%E9%A3%9E&Age=23
 var str1 = decodeURI(str);
 document.write("<br>" + str1);  //Name=张飞&Age=23
})


14. $.proxy()

Similar to the bind() method of the Function object, it accepts the function as the first parameter, the object as the second parameter, and returns a new function, which The function is called as a method of the second parameter object.

var arr = [1,3,5,7,9];
$(function () {
 var arr1 = $.makeArray(arr);
 document.write(arr1.join());  //输出 1,3,5,7,9
})

Fifteen, $.unique(array)

Delete duplicate elements in the element array

var arr1 = [1, 3, 5, 7, 9];
var arr2 = [2, 4, 6, 8, 10];
$(function () {
 var arr3 = $.merge(arr1, arr2);
 document.write(arr1.join() + "<br/>"); //1,3,5,7,9,2,4,6,8,10
 document.write(arr2.join() + "<br/>"); //2,4,6,8,10
 document.write(arr3.join() + "<br/>"); //1,3,5,7,9,2,4,6,8,10
})


  省略dest参数,extend方法原型中的dest参数是可以省略的,如果省略了,则该方法就只能有一个src参数,而且是将该src合并到调用extend方法的对象中去。

  要特别注意的一点是:后面的值会覆盖前面同名的值。

$(function(){
 $.extend({
 hello:function(){alert(&#39;hello&#39;);}  //该方法只有一个参数,意味着将hello方法合并到jQuery全局对象中去
 });
 $.hello(); //弹出 hello
})

   


  命名空间示例:

$(function(){
 $.extend({net:{}}); //扩展一个命名空间
 $.extend($.net,{
 hello:function(){alert(&#39;hello&#39;);} //将hello方法绑定到命名空间net里去
 })
 $.net.hello(); //通过net命名空间调用方法
})

   


 拷贝方法原型:

extend(boolean,dest,src1,src2,src3...)

其中第一个参数boolean表示是否进行深层拷贝。

$(function(){
 var result=$.extend( true, {},
 { name: "John", location: {city: "Boston",country:"USA"} },
 { last: "Resig", location: {state: "MA",country:"China"} } );
 alert(result.location.state); //输出 MA
 //result={name:"John",last:"Resig", location:{city:"Boston",state:"MA",county:"China"}}
 var result=$.extend( false, {},
 { name: "John", location: {city: "Boston",country:"USA"} },
 { last: "Resig", location: {state: "MA",country:"China"} } );
 alert(result.location.city); //输出 undefined
 //result={name:"John",last:"Resig",location:{state:"MA",county:"China"}} 注意没有city,只是合并了location,location里面的属性不管
})

   



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment