封装框架 设置文本与获取文本

// 实现 text 方法
itcast.fn.extend({
text: function(txt) {
// if条件中的代码表示读取
if(txt === undefined) {
var arr = [];
// 如果支持这两个属性中的任何一个
if("innerText" in this[0] || "textContent" in this[0]) {
// 要把获取到的所有元素的内容都要去除
this.each(function() {
arr.push(this.innerText || this.textContent);
});

return arr.join("");
}

// 获取多个(自己实现的功能)
this.each(function() {
// itcast.getInnerText(this) 的返回值是:string
// 拼接字符串 消耗的资源要很多,比使用数组push之后
// 在join要多
arr.push(itcast.getInnerText(this));
});
return arr.join("");
}

// 设置,最后要返回 当前获取到的所有元素
this.each(function() {
if("innerText" in this || "textContent" in this) {
this.innerText = txt;
this.textContent = txt;
} else {
// 兼容性处理
this.innerHTML = "";
var txtNode = document.createTextNode(txt);
this.appendChild(txtNode);
}
});

return this;
}
});

猜你喜欢

转载自ityehao.iteye.com/blog/2318090