我可以使用JavaScript来设置'name'属性吗? [英] Can I use JavaScript to set the 'name' attribute?
问题描述
根据 SitePoint (和我自己的实验),IE实现
同样根据 SitePoint , name
属性为只读。
方法我可以设置元素上的名称
属性?我需要这个用于单选按钮。如果可能,我想要一个没有jQuery的解决方案,因为我目前不使用库。
提前感谢!
正在谈论'name'的不同用法(见Anthony的注释)。它不是只读的,它只是有一个长期的IE错误(最多v7),其中在表单字段设置'name'只是部分有效。特别是单选按钮不能正常接受。
Microsoft认可的解决方案这里详细描述的是使用IE的版本的createElement调用的可怕的misfeature设置属性同时:
var radio = document.createElement('< input type =radioname =test value =a/>');
可能更好的方法就是使用好的老innerHTML,例如:
var div = document.createElement('div');
div.innerHTML ='< input type =radioname =testvalue =a/>'
var radio = div.firstChild;
According to SitePoint (and my own experiments), the IE implementation of "setAttribute()" is buggy and unreliable.
Also according to SitePoint, the name
attribute is read-only.
Is there another way I can set the name
attributes on elements? I need this for use with radio buttons. If possible, I'd like a solution without jQuery, as I'm currently not using the library.
Thanks in advance!
Sitepoint liesis talking about a different usage of ‘name’ (see Anthony's comment). It's not read-only, it's just there's a long-standing IE bug (up to v7) where setting ‘name’ on form fields is only partially effective. Radio buttons in particular don't accept it properly.
The Microsoft-endorsed solution, as detailed here is to use a horrific misfeature of IE's version of the createElement call to set attributes at the same time:
var radio= document.createElement('<input type="radio" name="test" value="a" />');
Probably a better way would simply be to use good old innerHTML, eg.:
var div= document.createElement('div');
div.innerHTML= '<input type="radio" name="test" value="a" />';
var radio= div.firstChild;
这篇关于我可以使用JavaScript来设置'name'属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!