Square brackets meaning string wont work [duplicat

2019-09-11 15:33发布

I am a bit stuck, trying to use this jquery line to enter a result from a select option into a text area

This doesnt work

  $("#id[txt_17]").val($(this).find("option:selected").attr("name"));

This does

$("#idtxt_17").val($(this).find("option:selected").attr("name"));

The [ ] are coded in via an oscommerce plugin and I have no idea of the importance of them, or what me removing them would do, but I am wondering if there is a workaround so I can leave them in. I tried creating a variable referencing the id but it still didnt work because of the square brackets.

Any help would be appreciated.

Thx

2条回答
▲ chillily
2楼-- · 2019-09-11 16:17

See: jQuery - Category: Selectors

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

replace:

$("#id[txt_17]").val

with:

$("#id\\[txt_17\\]").val

Example

查看更多
Bombasti
3楼-- · 2019-09-11 16:23

Escape the brackets:

$("#id\\[txt_17\\]")
查看更多
登录 后发表回答