可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have the following select with an unusual ID/Name attribute:
<select name="customfield_10021:1" id="customfield_10021:1" class="select cascadingselect-child">
This doesn't appear to allow me to select it with:
unit = $('#customfield_10021:1 option:selected').text();
http://jsfiddle.net/stzPQ/
uncaught exception: Syntax error, unrecognized expression: 1
How can I select this field? I've never even seen this particular syntax before, but it apparently works on submit.
Thanks!
Jared
回答1:
Escape the :
by using \\
unit2 = $('#customfield_10021\\:1 option:selected').text();
Updated jsfiddle
Or you can use document.getElementById("customfield_10021:1")
as the context for your selector.
var s = document.getElementById("customfield_10021:1");
unit2 = $('option:selected', s).text();
回答2:
You should escape the colon, so do this:
$("#customfield_10021\\:1")
You'd have:
unit = $('#customfield_10021\\:1 option:selected').text();
That's because the colon is a special caracter, and needs to be escaped with backslash.
Hope this helps. Cheers
回答3:
Escape the colon:
unit = $('#customfield_10021\\:1 option:selected').text();
See the jQuery FAQ.
Instead of using option:selected
you might want to just use .val()
to get the value of the <select>
:
unit = $('#customfield_10021\\:1').val();
回答4:
Try this:
unit = $('#customfield_10021\\:1 option:selected').text();
The :
is normally used for pseudo selectors, and the backslash needs to be doubled up in the string literal.
For the avoidance of doubt, the colon character is legal in ID and Name attributes.
回答5:
This works:
$('[id="customfield_10021:1"] option:selected').text()
Live demo: http://jsfiddle.net/stzPQ/2/
回答6:
I think that works:
unit = $("#customfield_10021\\:1 option:selected").text();
回答7:
Remember that a colon is used to deliminate a pseudo class, just as you do with option:selected
you will have to remove the colon from the id of your element:
<select name="customfield_10021_1" id="customfield_10021_1" class="select cascadingselect-child">
This is because jQuery is trying to use #customfield_10021:1
as id = customfield_10021
with a pseudo class of 1
which doesn't exist, thus the error.
回答8:
Another solution in JSF is to prevent the form name from prepending each id.
This can be done with the prependId="false" in the form tag :
<h:form id="gestion_clefs" prependId="false">