jQuery 源码问题扩展
# IE 和 Opera 会用 name 代替 ID 返回元素的问题
IE works correctly on elements that CAN'T have a name attribute. It works incorrectly, however, on elements that can.
As I researched this, I found a function in JavaScript I've never used before:
HTMLCollection.namedItem( String name )
This function seeks for any element within the collection whose id attribute value matches the name specified in the call. If it doesn't find one, it searches for any element whose name attribute matches the name specified in the call. The function returns the first element object it finds that meets the criteria, or null if it can't find one.
My first thought was, Microsoft has their document.getElementById calling their namedItem() function. But then I stepped back and realized through my experiment that IE seems to be matching against both name and id at the same time to match the value.
As you'll notice below, I have two elements for each part of the experiment. The first has the name attribute filled with the id value "my[Element]" I'm wanting to look for. I fill the second element's id attribute with the same value. IE, parsing from the top of the document down, finds the element with the name="my[Element]" first and automatically takes it... it doesn't even wait to see if it can find one with an id that matches first.
I can only assume this was done for optimizing this "convenience feature", but makes for some serious puzzlement and aggravation in troubleshooting why the element a developer can't get to who happens to name/id things in a way similar to what happens in my experiment. Whatever reason, they did it, it's wrong. Please be careful in how you name/id things
jQuery 通过 $().find(selector)
通过查找子节点来解决这个问题的。
参考: