教程 jquery tutorial

常用工具函数

jQuery 不仅提供 DOM 操作和 AJAX 功能,还包含丰富的工具函数,便于处理数组、对象和字符串等常见任务。

1. $.each()

用于遍历数组或对象。

js
$.each([1, 2, 3], function (index, value) {
  console.log(index + ": " + value);
});

2. $.extend()

合并对象,常用于配置合并。

js
var defaults = { a: 1, b: 2 };
var options = { b: 3, c: 4 };
var result = $.extend({}, defaults, options);
console.log(result); // {a:1, b:3, c:4}

3. $.trim()

去除字符串两端空白。

js
var str = "  hello world  ";
console.log($.trim(str)); // "hello world"

4. $.isArray()

判断是否为数组。

js
console.log($.isArray([1, 2, 3])); // true
console.log($.isArray("abc")); // false

5. $.parseJSON()

解析 JSON 字符串(现代浏览器已推荐使用 JSON.parse)。

js
var jsonStr = '{"name":"jQuery"}';
var obj = $.parseJSON(jsonStr);
console.log(obj.name); // jQuery

示例代码

在线代码演示
源码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div id="output" style=" white-space: pre-wrap; font-family: monospace; background: #f9f9f9; padding: 10px; border: 1px solid #ccc; " ></div>

<script> $(function () { // 定义一个函数用于输出文本到页面 function output(text) { $("#output").append(text + "\n"); }

var arr = [&quot;苹果&quot;, &quot;香蕉&quot;, &quot;橙子&quot;];
$.each(arr, function (i, val) {
  output(i + &quot;: &quot; + val);
});

var obj1 = { x: 1, y: 2 };
var obj2 = { y: 3, z: 4 };
var merged = $.extend({}, obj1, obj2);
output(JSON.stringify(merged));

var str = &quot;  测试字符串  &quot;;
output(&quot;'&quot; + $.trim(str) + &quot;'&quot;);

}); </script>