Square brackets meaning string wont work [duplicate]

对着背影说爱祢 提交于 2019-12-13 20:51:36

问题


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


回答1:


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




回答2:


Escape the brackets:

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


来源:https://stackoverflow.com/questions/18319195/square-brackets-meaning-string-wont-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!