0

请忍受伪代码和格式,我真的不记得我头顶上的代码了。

在 IE9 及更低版本中,我知道您可以使用 setAttribute() 方法设置属性和属性,但在 IE10 中似乎已经通过单独分隔属性和属性来更改。

甚至做类似的事情

element.setAttribute("className", "myClass");

设置元素显示为

<tag className = "myClass" />

它甚至没有设置属性。

在我的代码中,我有一个 JSON 列表,用于存储属性/属性的名称和值,我只需使用 setAttribute();

createElement(tag, list)
{
    //pseudocode
    var element = createElementWithTag(tag);
    for each(attr in attributes)
       if (attributes.hasOwnKey(attr))
           element.setAttribute(attr, attributes[attr]);
}

这适用于 IE7-9,但在 IE10 中完全失败。

有什么方法可以设置属性和属性而不需要它是哪种类型(attr 或 prop)?

我什至想不出一种动态设置属性的方法,而无需对要更改的属性进行硬编码。

解决方案可能也会有所帮助。

4

1 回答 1

1

我认为这样的事情是你想要的:

function tag(tag, attribs) {
    if(tag.charAt) tag = document.createElement(tag);
    var alias = {
        htmlFor: "for",
        className: "class"
    }, prop;
    for (prop in attribs) if (attribs.hasOwnProperty(prop)) {
        if("style" == prop) tag.style.cssText = attribs[prop];
        try {
            tag[prop] = attribs[prop];
        } catch (h) {
            tag.setAttribute( alias[prop] || prop, attribs[prop]);
        }
    }
    return tag;
}


//test it:
tag("a", {href:"/", target:"_blank", innerHTML:" some text ", className: "1 2 3"}).outerHTML 

在 IE8 和 Chrome 中测试。

如果有人知道更多 dom->attrib 映射(如 htmlFor),请将它们编辑为答案,谢谢!

于 2013-10-11T06:43:43.147 回答