如果表单包含相应命名的输入,如何访问表单的 id 或样式?
在此示例中,
<form id="form1">
<input type="text" name="style">
</form>
<form id="form2">
<input type="text" name="id">
</form>
您无法访问 form1 的样式声明或 form2 的 id,因为命名输入隐藏了相应的属性。
有解决方法吗?
编辑: 显然,getAttribute
适用于id
。但不适用于 style
、childNodes
、tagName
等。
我正在寻找这样的东西:
getDomProp = (function() {
if (window.__lookupGetter__) {
var cleanForm = document.createElement('form');
return function(form, key) {
// works in Firefox, fails in Opera:
return cleanForm.__lookupGetter__(key).call(form);
};
} else if (Object.getOwnPropertyDescriptor) {
return function(form, key) {
// does not work at all:
// return Object.getOwnPropertyDescriptor(cleanForm, key).get.call(form);
}
} else {
throw 'Not supported.';
}
})();
In this example
<form id="form1">
<input type="text" name="style">
</form>
<form id="form2">
<input type="text" name="id">
</form>
you cannot access form1's style declaration or form2's id, since the named inputs shadow the corresponding properties.
The same holds for other properties too
Any workarounds?
Edit:getAttribute
works for id
, obviously. But not for style
, childNodes
, tagName
etc.
I'm looking for something like this:
getDomProp = (function() {
if (window.__lookupGetter__) {
var cleanForm = document.createElement('form');
return function(form, key) {
// works in Firefox, fails in Opera:
return cleanForm.__lookupGetter__(key).call(form);
};
} else if (Object.getOwnPropertyDescriptor) {
return function(form, key) {
// does not work at all:
// return Object.getOwnPropertyDescriptor(cleanForm, key).get.call(form);
}
} else {
throw 'Not supported.';
}
})();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这仍然有效:
PS。不要在生产代码中命名您的输入:)
This will still work:
PS. Don't name your inputs that in production code :)
使用
getAttribute
获取对应的表单属性:http://jsfiddle.net/6d8sx/ 3/编辑:
getAttribute
似乎适用于 IE9、FF5(不确定其他版本)。但是,以这种方式命名元素会导致出现问题(如果不是您的代码,那么某些库或插件可能会感到困惑)。
Use
getAttribute
to get the corresponding form attributes: http://jsfiddle.net/6d8sx/3/Edit:
getAttribute
seems to work in IE9, FF5 (not sure about others).However, naming your elements that way will cause problems down the line (if not your code, then some library or plugin might get confused).
使用
.getAttribute(); 访问它们
http://reference.sitepoint.com/javascript/Element/getAttribute
Access them using
.getAttribute();
http://reference.sitepoint.com/javascript/Element/getAttribute
使用 jquery:
$('#form1').css()
或$('#form2').attr('id')
。yuse jquery:
$('#form1').css()
, or$('#form2').attr('id')
.