获取跟设置目标元素的属性值

获取和设置目标元素的属性值

api的应用场景是:获取和设置目标元素的属性值

 

关于ZYC.dom.g的资料:http://zhangyaochun.iteye.com/blog/1439262

 

 

 

1、提供一个attribute名的转换的api

 

/*
*_NAME_ATTRS *
*fix the difference between ie8 and low edition*
*relay on ZYC.browser*
*/
ZYC.dom._NAME_ATTRS = (function(){
     var result = {
        'cellpadding' : 'cellPadding',
        'cellspacing'  : 'cellSpacing',
        'colspan'       : 'colSpan',
        'rowspan'      : 'rowSpan',
        'valign'          : 'vAlign',
        'usemap'       : 'useMap',
        'frameborder': 'frameBorder'
     }
      if(ZYC.browser.ie < 8){
           result['for'] = 'htmlFor';
           result['class'] = 'className';
      }else{
           result['htmlFor'] = 'for';
           result['className'] = 'class';
      }
      return result;
})();

 

2、获取目标元素的属性值

 

/*
*getAttr-get the attribute value form the element with the key*
*@function*
*@param {string||HTMLElement} element*
*@param {String} key*
*@return {String|null}*
*/
ZYC.dom.getAttr = function(element,key){
        element = ZYC.dom.g(element);
	if(key == 'style'){
	   return element.style.cssText;
	}
	//use ZYC.dom._NAME_ATTRS
	//fix ie difference
	key = ZYC.dom._NAME_ATTRS[key] || key;
        return element.getAttribute(key);
};

 

3、设置目标元素的属性值

 

/*
*setAttr-set the attribute value for the element with the key*
*@function*
*@param {string||HTMLElement} element*
*@param {String} key*
*@param {String} value*
*@return {HTMLElement}*
*/
ZYC.dom.setAttr = function(element,key,value){
        element = ZYC.dom.g(element);
		if(key == 'style'){
		   element.style.cssText = value;
		}else{
		   key = ZYC.dom._NAME_ATTRS[key] || key;
		   element.setAttribute(key,value);
		}
        return element;
};