Internet Explorer 10 - (Javascript 或 jQuery) 如何在不知道属性和属性是什么类

Internet Explorer 10 - (Javascript or jQuery) How to change attributes and property without knowing which type it is (dynamic changes)?

本文关键字:属性 不知道 是什么 Explorer Javascript jQuery Internet      更新时间:2023-09-26

请耐心等待伪代码和格式,我真的不记得我头顶上的代码。

在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(?

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

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

我认为这样的东西是你想要的:

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(,请将它们编辑到答案中,谢谢!