登录/注册
小开开
2649
占位
2
占位
0
浏览量
占位
粉丝
占位
关注
Zepto 相关 DOM 操作
小开开
2020-08-12 20:39:16 2020-08-12
306
0

一、DOM 元素的处理

1、获取页面所有的标签元素

let divTags = $("div");

2、获取 ID 为 app 的元素

let app = $("#app");

3、创建元素

$("<h2>创建DOM标签</h2>");

4、创建带有属性的元素

$("</p>", {
text: "创建带有属性的元素",
id: "app",
css: {
color: "darkblue"
}
});

5、当页面 ready 时,执行回调函数

Zepto(function($) {
alert("Ready to Zepto!");
});

二、字符串&数组&对象处理

1、“骆驼命名法”转换字符串

let tf = $.camelCase("xiao-kang"); // xiaoKang
let tf2 = $.camelCase("helloZepto!"); // helloZepto

:如果待转换的字符串已经是“驼峰法”形式,则不会再进行转化。

2、检查父节点是否包含指定 DOM 节点

let flag = $.contains(parent, node); // true || false

:若两者是相同节点,则返回false

3、遍历数组元素

let arr = ["a", "b", "c", "hh", "gd", "zz"];
$.each(arr, function(index, item) {
console.log("item %d is: %s", index, item); // item 'index' is: 'item'
});

4、以 key-value 键值对方式遍历对象

$.each(
{
name: "zepto.js",
size: "98k"
},
function(key, value) {
console.log("%s : %s", key, value); // key :value
}
);

5、源对象扩展目标对象(对象合并)

let obj1 = {
num: "A001",
tg: "kk"
},
obj2 = {
name: "zxk",
tg: "kang"
};
$.extend(tag1, tag2); // {num: 'A001',name: 'zxk',tg: 'kang'}
$.extend(true, tag1, tag2); // {num: 'A001',name: 'zxk',tg: 'kang'}

:通过源对象扩展目标对象的属性,源对象属性将覆盖目标对象属性(后者覆盖前者);默认情况下为浅拷贝浅复制);如果第一个参数为true,则表示深度拷贝深度复制)。

6、Zepto.fn 对象

$.fn.empty = function() {
return this.each(function() {
this.innerHTML = "";
});
};

Zepto.fn是一个对象,它拥有 Zepto 对象上所有可用的方法。

7、根据条件处理数组

$.grep([1, 2, 3], function(index, item) {
return item > 1; // [2,3]
});

8、返回数组指定元素索引值

let aIndex = $.inArray("a", ["c", "a", "d"]);
console.log(aIndex); // 1
let bIndex = $.inArray("b", ["c", "d", "a", "b", "z"], 1);
console.log(bIndex); // 3
let cIndex = $.inArray("y", ["z", "x", "k"], 1);
console.log(cIndex); // -1

:返回数组中指定元素的索引值(以0为基数);如果没有找到该元素则返回**-1[fromIndex]参数可选,表示从哪个索引值开始向后**查找。

9、判断是否为数组 Array

let arr = ["1"],
str = "aaa";
$.isArray(arr); // true
$.isArray(str); // false

10、判断是否为函数 Function

let fn = function() {},
str = "fn";
$.isFunction(fn); // true
$.isFunction(str); // false

11、判断是否为纯粹的对象 Object

$.isPlainObject({}); // true
$.isPlainObject(new Object()); // true
$.isPlainObject(new Date()); // false
$.isPlainObject(window); // false

12、判断是否为 window 对象

$.isWindow(window); // true
$.isWindow(document); // false

13、数组元素过滤

```javascript

let arr = [1, 3, 5, null, 7, 9, undefined, 11];
let newArr = $.map(a12, function(item, index) {
if (item > 1) return item * item;
});
console.log(newArr); // [9, 25, 49, 81, 1

暂无评论