如何访问包含相应命名输入的表单的id或样式

How to access a form's id or style if it contains accordingly named inputs?

本文关键字:输入 表单 id 样式 何访问 访问 包含相      更新时间:2023-09-26

在这个例子中

<form id="form1">
    <input type="text" name="style">
</form>
<form id="form2">
    <input type="text" name="id">
</form>

不能访问form1的样式声明或form2的id,因为命名的输入遮蔽了相应的属性。

其他属性也一样

工作区吗?

编辑:

显然,getAttributeid起作用。stylechildNodestagName等均不存在

我在找这样的东西:

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.';
    }
})();

小提琴

仍然可以:

form.getAttribute('id');

p。不要在产品代码中命名你的输入:)

使用getAttribute获取相应的表单属性:http://jsfiddle.net/6d8sx/3/

alert('id: ' + form.getAttribute('id'));

编辑: getAttribute似乎在IE9, FF5中工作(不确定其他)。

然而,以这种方式命名元素会导致问题(如果不是你的代码,那么一些库或插件可能会混淆)。

使用.getAttribute();访问它们http://reference.sitepoint.com/javascript/Element/getAttribute

使用jquery: $('#form1').css(),或$('#form2').attr('id') .