Get element by id via regex jQuery
Html element contains complex & unique id, composed from namespace as prefix and incremented index - as postfix.
I try do it with wildcard expression for id.
If to use simple way without namespace, that it works fine:
$j("[id*=service_selected_]").click(function(){
...
In order to keep uniqueness,i need provide namespace part within id,but it doesn't r开发者_如何学Cesolved this way:
var selId = "'" + '[id*=' + namespace + '_service_selected_]' + "'";
$j(selId).click(function(){
...
Below the .jsp part:
<c:forEach var="package" items="${packages.page}" varStatus="status">
<tr>
<td>
${package.name}
</td>
<td id="<portlet:namespace/>_service_price_${status.index}">${package.price}</td>
<td >
<input type="checkbox" name="service_id" value="${package.id}" id="<portlet:namespace/>_service_selected_${status.index}">
</td>
</tr>
</c:forEach>
Well, since we are all suggesting different versions of the same code, here's mine:
var namespace = 'test';
var id = '_service_selected_';
$(["[id^=", namespace, "_", id, "_]"].join(''));
I've also done some speed tests on all the suggestions posted so far. Mine happens to be the fastest on Firefox and Chrome and the second best on IE8. Josh Stodola's doesn't work at all.
Here's the test suite: http://jsbin.com/igate (Editable via http://jsbin.com/igate/edit)
Here are the results:
Firefox
select_Phil 37 ms 36 selected
select_Ghommey 120 ms 36 selected
select_Josh_Stodola 1077 ms 0 selected
select_brianpeiris 31 ms 36 selected
Chrome
select_Phil 17 ms 36 selected
select_Ghommey 108 ms 36 selected
select_Josh_Stodola 290 ms 0 selected
select_brianpeiris 15 ms 36 selected
IE8
select_Phil 69 ms 36 selected
select_Ghommey 300 ms 36 selected
select_Josh_Stodola 1632 ms 0 selected
select_brianpeiris 73 ms 36 selected
How about
var selId = "[id*=" + namespace + "_service_selected_]";
$j(selId).click(function(){
...
I think you've got confused with too many quotation marks!
I would use the startsWith selector to get the namespace of elements, and then query against it to get your matches...
var namespace = "test";
var itemspace = "_service_selected_";
var ns = $("[id^=" + namespace + "]");
var nsItems = $("[id*=" + itemspace + "]", ns);
You might search twice
$j("[id*=" + namespace + "]").filter("[id*=service_selected_]").click(function(){
精彩评论