Why my jQuery selector can't find my element by id?
I have a code with a simple jQuery selector usage:
$("label").each(function () {
var target = $("#" + $(this).attr("for"));
});
I'm using PrimeFaces, so the HTML looks like:
<label for="j_idt23:txtNumb开发者_如何学JAVAer">Number:</label>
<input id="j_idt23:txtNumber" name="j_idt23:txtNumber" type="text" value="0" class="ui-inputfield ui-widget ui-state-default ui-corner-all" />
But it raises an error: "Syntax error, unrecognized expression: txtNumber"
.
What I'm doing wrong?
The :
symbol is one of the selectors' wildcards used by jQuery (that like pointed in the comments, represents a pseudoclass for the element, i.e., input:disabled
). So, it is trying to interpret :
as a wildcard and not as a part of your id
. jQuery think your id is j_idt23
and the pseudoclass is txtNumber
(wich is invalid, sure).
Just add the \\
before it and jQuery will interpret as literal text.
Your code will look like this:
$("label").each(function () {
var target = $("#" + $(this).attr("for").replace(":", "\\:"));
});
Since your using PrimeFaces there is a function PrimeFaces.escapeClientId()
that will escape the JSF ID into a usable jQuery ID.
$("label").each(function () {
var target = $(PrimeFaces.escapeClientId($(this).attr("for")));
});
Think about the wasy jQuery handles selectors:
# denotes an id: '#id'
. denotes a class: '.class'
: denotes a pseudo class: ':pseudo_class'
So when your doing your selection it is expanding to:
$("#j_idt23:txtNumber")
Meaning find an element with id = 'j_idt23' and pseudo class 'txtNumber' but txtNumber isnt a valid pseudo class, and jQuery is confused.
Change it to something like "j_idt23_txtNumber"
There is also an other approach in JSF 2.0. If you're comfort with, try to change the separator char directly via "web.xml"
<context-param>
<description>
Declares the separator char for ids (default is ':')
</description>
<param-name>javax.faces.SEPARATOR_CHAR</param-name>
<param-value>§</param-value>
</context-param>
This context param changes the separator char globally, e.g. j_idt23:txtNumber becomes j_idt23§txtNumber.
精彩评论