Javascript Array ID's

2019-07-30 13:27发布

I've got a HTML page containing elements that I need to access using JQuery. Here is an example of how the form elements are identified:

<div id="nItemID[766]Line" class="formLine ">
   <span id="nItemID[766]Label" class="formLabel alignTop">Téléphone:</span>
   <input id="nItemID[766]Field" class="formField" type="text" maxlength="11" value="" name="nItemID[766]" style="width: 300;">
</div>

When I try to show the ID of a particular element, it tells me: nItemID[766]Label, for example. But when I type that code, it doesn't find anything...

alert( $("#nItemID[766]Field").val() );

Could someone help me with the way to access those particular elements ?

Thank you!

4条回答
可以哭但决不认输i
2楼-- · 2019-07-30 14:02

You'll have to escape the square brackets with backslashes:

alert($('#nItemID\\[766\\]Field').val());

It's a little bit questionable to have "id" values like that, but I've been in situations in which they're hard to avoid.

edit — note that you need two backslashes in the string so that the jQuery selector interpreter can "see" them; that is, you need to leave a single backslash in the string, and the way to do that in JavaScript is to double the backslash I hate explaining that.

edit again — Here's what the HTML 5 draft has to say about "id" attributes:

3.2.3.1 The id attribute

The id attribute specifies its element's unique identifier (ID). [DOMCORE]

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

An element's unique identifier can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragment identifiers, as a way to target an element when scripting, and as a way to style a specific element from CSS.

Identifiers are opaque strings. Particular meanings should not be derived from the value of the id attribute.

No rules about the values of "id" attributes, in other words, other than that they cannot contain spaces.

查看更多
小情绪 Triste *
3楼-- · 2019-07-30 14:02

That is invalid HTML. [ and ] are not valid characters in ids. You can use them in names like you already do on your input element, but not in ids.

You should change your ids to be something like nItemID_766_Field. Then it will be a valid id and you can easily just change the number for each nItem.

Edit

As Pointy pointed out it is valid in HTML 5. So you shouldn't need to change your id's unless you are trying to conform to HTML 4.

查看更多
爷的心禁止访问
4楼-- · 2019-07-30 14:07

Try instead document.getElementById("nItemID[766]Field").value. Apparently jQuery doesn't support ids with braces.

查看更多
迷人小祖宗
5楼-- · 2019-07-30 14:09

Your IDs are invalid, see this.

查看更多
登录 后发表回答