我知道
jquery .attr()对属性名称不区分大小写,但是当我从代码创建的文档创建元素时,它会区分大小写.
这是解释问题的代码示例:
var mydoc = document.implementation.createDocument('a:b','c',null);
var myElement = mydoc.createElement("myelement");
myElement.setAttribute("attr1","val1");
alert($(myElement).attr("attr1"));//val1
alert($(myElement).attr("Attr1"));//undefined! , why?
var myElement2 = document.createElement("myelement2");
myElement2.setAttribute("attr1","val1");
alert($(myElement2).attr("attr1"));//val1
alert($(myElement2).attr("Attr1"));//val1
我在chrome 22.0和jquery 1.8上测试过它.
更新:
似乎这不是jquery问题.
console.log(myElement.attributes['attr1']); //val1 , OK
console.log(myElement.attributes['Attr1']); //undefined ???
console.log(myElement2.attributes['attr1']); //val1 , OK
console.log(myElement2.attributes['Attr1']); //val1 , OK
最佳答案 您需要创建html的documentType(
https://developer.mozilla.org/en-US/docs/DOM/DOMImplementation.createDocumentType)并将其作为第3个参数传递给createDocument方法
var dt = document.implementation.createDocumentType('html', '', '');
var mydoc = document.implementation.createDocument('a:b','c',dt);
var myElement = mydoc.createElement("myelement");
myElement.setAttribute("attr1","val1");
console.log(myElement.attributes['attr1']); //val1 , OK
console.log(myElement.attributes['Attr1']); //val1 , OK !!!