问题
I'm working on embedding a flash app in a webpage using the Satay method:
<object type="application/x-shockwave-flash" data="embeddy.swf"
id="embeddy" name="embeddy">
<param name="movie" value="embeddy.swf" />
</object>
I want flash to provide the correct objectID
in ExternalInterface.objectID
, which means I need to set both the name
and id
attributes for the object
.
Normally I try to avoid naming collisions with elements in HTML, but is there anything wrong with setting both attributes to the same value in this case?
What about HTML forms? Does anyone feel that it's worthwhile to set a(n) ( input
| select
| textarea
) element's name
and id
attributes to the same value?
回答1:
You use IDs for JavaScript manipulation.
You use Names for form field submission.
The two are not related. So setting both to the same value is OK, but it is not required.
回答2:
Not only is it okay, it's quite common.
IDs are used for Javascript (and to a lesser extent, for CSS).
Names are used for form fields to specify the name for the submitted value.
However older versions of IE have known bugs that mean you're almost forced to specify them both the same in many cases. (assuming you want to support those older versions of IE, of course!)
The one thing to bear in mind though is that that IDs must be unique. Therefore, if you have radio buttons which all have the same name, you can't use the same ID for them all. In most other cases though, it's perfectly fine to have them the same.
回答3:
Yup! This is absolutely fine.
id is the client-side identifier (for when looking up an element in the DOM)
name is used during form submission to POST/GET the values.
Outside of an input element there should be no need to use name at all. But giving input elements an id allows them to be looked up in the DOM in a consistent fashion.
回答4:
I just discovered the HTML4 answer to my question:
The id and name attributes share the same name space. This means that they cannot both define an anchor with the same name in the same document. It is permissible to use both attributes to specify an element's unique identifier for the following elements:
A, APPLET, FORM, FRAME, IFRAME, IMG, and MAP
. When both attributes are used on a single element, their values must be identical.
Now, I assume that the rule being applied to applet
and iframe
should, by extension, work for object
and embed
tags. In any event, using an identical name & id has produced no unusual events to date.
回答5:
I do it all the time (mostly because some browsers in the past - IE comes to mind - only use the name parameter when sending the form data). Using id's makes form validation code much cleaner, IMO.
来源:https://stackoverflow.com/questions/4128001/is-it-ok-for-an-html-element-to-have-the-same-name-as-its-id