问题
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