InternetExplorer10-(Javascript或jQuery)如何更改属性和属性而不知道它是哪种类型(动态更改)?
请容忍这些伪代码和格式,我真的记不住这些代码了 在IE9及以下版本中,我知道您可以使用setAttribute()方法设置属性和属性,但在IE10中,通过将属性和属性分开,这一点似乎有所改变 甚至做类似的事情InternetExplorer10-(Javascript或jQuery)如何更改属性和属性而不知道它是哪种类型(动态更改)?,javascript,properties,attributes,internet-explorer-10,setattribute,Javascript,Properties,Attributes,Internet Explorer 10,Setattribute,请容忍这些伪代码和格式,我真的记不住这些代码了 在IE9及以下版本中,我知道您可以使用setAttribute()方法设置属性和属性,但在IE10中,通过将属性和属性分开,这一点似乎有所改变 甚至做类似的事情 element.setAttribute("className", "myClass"); 将元素设置为显示为 <tag className = "myClass" /> 这在IE7-9中运行良好,但在IE10中完全失败 有没有什么方法可以设置属性和属性,而不使用它的类型(
element.setAttribute("className", "myClass");
将元素设置为显示为
<tag className = "myClass" />
这在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),请将它们编辑到答案中,谢谢 成功了,非常感谢!如果我有足够的声誉我会投票。。。我对try-catch块有点担心,因为它们会减慢速度,即使在一个小的网页上这可能没有多大关系,我还是决定这样做:if(tag[prop!=“undefined”)tag[prop]=attribs[prop]else tag.setAttribute[prop,attribs[prop]);但不确定这是否是一个更好的实现……另外,您能否解释一下为什么使用tag.setAttribute(别名[prop]| | prop,attribs[prop]),而不仅仅是tag.setAttribute[prop,attribs[prop])?@MaskedTwilight:如果您的if语句始终为true,请去掉未定义的引号。唯一尝试的是设置一个属性,该属性非常快,可以在不产生影响的情况下减慢速度。如果您严格使用它,您可以将其删除。尝试的目的是在设置某些属性时阻止像embed这样的奇怪标记上的异常IE中不喜欢设置的属性。需要别名将setAttribute调用的“className”转换为“class”。它在attrib名称和属性名称之间均匀化。
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