admin管理员组文章数量:1356011
I am creating this JS function that creates an element The function takes two parameters strName and objAttributes
function createElement( strName, objAttributes )
{
var elem = document.createElement(strName);
for ( var i in objAttributes )
elem.setAttribute(i, objAttributes[i]);
return elem;
}
This works fine in Fx, but not in MSIE I know that the setAttibute method is buggy and the proposed workaround is
elem.attr = 'val';
But right now I have no idea how to write this inside my loop.
I have tried both elem.style and elem['style'] but none of them works.
Can anyone give me some advice,
thanks in advance
t
I am creating this JS function that creates an element The function takes two parameters strName and objAttributes
function createElement( strName, objAttributes )
{
var elem = document.createElement(strName);
for ( var i in objAttributes )
elem.setAttribute(i, objAttributes[i]);
return elem;
}
This works fine in Fx, but not in MSIE I know that the setAttibute method is buggy and the proposed workaround is
elem.attr = 'val';
But right now I have no idea how to write this inside my loop.
I have tried both elem.style and elem['style'] but none of them works.
Can anyone give me some advice,
thanks in advance
t
Share Improve this question edited Mar 28, 2009 at 1:31 Scott Evernden 40k15 gold badges80 silver badges84 bronze badges asked Mar 28, 2009 at 0:58 ThomasThomas3 Answers
Reset to default 6Use elem[i]
.
function createElement( strName, objAttributes )
{
var elem = document.createElement(strName);
for ( var i in objAttributes )
elem[i] = objAttributes[i];
return elem;
}
You can't just swap setting properties and setAttribute.
You have to be careful with setting properties on an element in place of using setAttribute. Style properties and event handlers need to be carefully written, and those attributes that used to be minimized in html (disabled, multiple, readonly) have browser specific valid values.
Also, if you set element.class="mynewclass", you'll get an error, because class is a reserved javascript word, though it is perfectly safe to use it as a string in a setAttribute assignment. THe property name is '.className', and the proper name for a label's 'for' attribute is 'htmlFor'.
Let jQuery handle the cross-browser nonsense...
$(elem).attr(i, objAttributes[i]);
本文标签: domJavaScript setAttribute alternativeStack Overflow
版权声明:本文标题:dom - JavaScript setAttribute alternative - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744043396a2581080.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论