根据this blog post,可以将DOM元素作为window
对象的命名属性(基于它们的name
属性)引用。上面的代码显示表单确实可以作为window.aform
访问。然而,为什么在迭代window
的所有属性时找不到属性?
<html>
<body>
<form name='aform'>
</form>
<script>
// get all properties, including non-enumerable ones: http://stackoverflow.com/a/8024294/274677
function getAllProperties(obj){
var allProps = [], curr = obj;
do {
var props = Object.getOwnPropertyNames(curr)
props.forEach(function(prop){
if (allProps.indexOf(prop) === -1)
allProps.push(prop)
})
} while(curr = Object.getPrototypeOf(curr))
return allProps
}
var findIn = function(x,y) {
var ps = getAllProperties(x);
for (var i = 0 ; i < ps.length; i++) {
var propertyName = ps[i];
try {
if (x[propertyName]===y)
return 'found as property ['+propertyName+']';
} catch (e) {
console.log('failed to read property ['+propertyName+'] due to: ['+e.name+']');
}
}
return "not found";
}
console.log(findIn(window, window.aform));
console.log(window['aform']===window.aform);
console.log(window.aform);
</script>
</body>
</html>
当上面的页面加载时,我在控制台上看到:
not found
true
<form name="aform"></form>
答案 0 :(得分:1)
Some browsers add the form reference as a property to the window
object, some only make it available so that you can read it like a property but it's not actually added as a property.
When I try it in Firefox it finds the property, but in Chrome, IE and Edge it's not found.
The safest way to get the form by name is by using the document.forms
collection, where it's clearly defined that the forms are available.