Is it ok for an HTML element to have the same [nam

2019-01-18 08:22发布

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?

5条回答
我只想做你的唯一
2楼-- · 2019-01-18 08:59

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-18 09:06

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.

查看更多
趁早两清
4楼-- · 2019-01-18 09:12

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.

查看更多
贪生不怕死
5楼-- · 2019-01-18 09:15

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.

查看更多
做个烂人
6楼-- · 2019-01-18 09:19

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.

查看更多
登录 后发表回答