When to use setAttribute vs .attribute= in JavaScript?

后端 未结 9 2321
闹比i
闹比i 2020-11-22 11:44

Has a best-practice around using setAttribute instead of the dot (.) attribute notation been developed?

E.g.:

myObj.setAttr         


        
9条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 12:19

    This looks like one case where it is better to use setAttribute:

    Dev.Opera — Efficient JavaScript

    var posElem = document.getElementById('animation');
    var newStyle = 'background: ' + newBack + ';' +
    'color: ' + newColor + ';' +
        'border: ' + newBorder + ';';
    if(typeof(posElem.style.cssText) != 'undefined') {
        posElem.style.cssText = newStyle;
    } else {
        posElem.setAttribute('style', newStyle);
    }
    

提交回复
热议问题