/** *@name getOwnJssData 获取设置data-jss这种方式的数据 *@param el *@param needInit *@return {Object} data / function getOwnJssData(el,needInit){ var data = el.__jssData; if(!data){ //匹配上key为data-jss适合在每个标签里面加data-jss=""这种方式 var s = el.getAttribute('data-jss'); if(s){ //进行{}包裹 if (!/^\s*{/.test(s)) { s = '{' + s + '}'; } //evalExp会把字符串转换成对象 //赋值给data和el.__jssData data = el.__jssData = evalExp(s); }else if(needInit){ data = el.__jssData = {}; } } //返回数据对象 return data; }
/** *@name getOwnJss *@param el *@param attributeName 指定对应的key为attributeName *@see getOwnJssData */ getOwnJss:function(el,attributeName){ var data = getOwnJssData(el); if(data && (attributeName in data)){ return data[attributeName]; } return undefined; }
结论:
- getOwnJss只是返回data-jss这种方式的数据,而且是第一个匹配元素的对应数据
/** *@name setJss *@param el *@param attributeName *@param attributeValue *@see getOwnJssData */ setJss:function(el,attributeName,attributeValue){ var data = getOwnJssData(el,true); data[attributeName] = attributeValue; }
/** *@name removeJss *@param el *@param attributeName *@see getOwnJssData */ removeJss:function(el,attributeName){ var data = getOwnJssData(el); if(data && (attributeName in data)){ //采用delete方式删除 delete data[attributeName]; //返回标志位,true代表删除操作完成 return true; } //返回标志位,默认false return false; }
/** *@name getJss *@param el *@param attributeName *@see getOwnJssData *@see getRuleData */ getJss:function(el,attributeName){ var data = getOwnJssData(el); if(data && (attributeName in data)){ return data[attributeName]; } //id var getRuleData = Jss.getRuleDate, id = el.id; //id是有规范的"#"+id if(id && (data = getRuleData("#" + id)) && (attributeName in data)){ return data[attributeName]; } //name var name = el.name; //name是有规范的"@"+name if(name && (data = getRuleData("@" + name)) && (attributeName in data)) { return data[attributeName]; } //className var className = el.className; //className是有规范的"."+className if(className){ //支持"classNameA classNameB classNameC" var classNames = className.split(" "); for(var i = 0;i<classNames.length;i++){ if((data = getRuleData('.'+classNames[i])) && (attributeName in data)){ return data[attributeName]; } } } //tagName var tagName = el.tagName; if(tagName && (data = getRuleData(tagName)) && (attributeName in data)){ return data[attributeName]; } return undefined; }
从getJss的设计得出一些结论:
- 获取的有一定的优先顺序:data-jss > #id > @name > .className > tagName