I have the following code:
<li class="zoneName"><a href="/Default.aspx?PageID=4869007">CYKF</a></li>
<li class="zoneName"><a href="/Default.aspx?PageID=4868459">YKA</a></li>
I need to add and ID to each of the < li > tags in this list. I need that ID to be the number at the end of the href string. Below is what I'd like it to be
<li class="zoneName" id="4869007"><a href="/Default.aspx?PageID=4869007">CYKF</a></li>
<li class="开发者_如何学GozoneName" id="4868459"><a href="/Default.aspx?PageID=4868459">YKA</a></li>
Any help is appreciated.
Is the PageID in the anchor tag written in a server-side loop? Couldn't you modify it to write it to the <li>
tag as well?
If it must be jQuery, here you go
$("li a").each( function() {
var match = /PageId=(\d+)$/.exec(this.href);
if (match) $(this).parent("li")[0].id = match[1];
});
you can do it like that:
demo: http://jsfiddle.net/qnEAu/
$('ul > li > a').each(function(){
var element = $(this)
var tempid = element.attr('href').split('=')
element.parent('li').attr('id', tempid[tempid.length - 1])
})
note that it is not w3c valid to use numbers only as ID's
$("li>a").each(function(i,el){
var id = $(this).attr("href").split("=")[1];
$(this).parent().attr("id", id);
})
If the href
is always going to only have integers in the PageID
portion of the query, and the PageID
would be the only part of the query with integers:
$('li').each( function() {
var href_val = $(this).children('a').attr('href');
var regex = '\b[0-9]+\b';
var new_id = new RegExp(regex, href_val);
$(this).attr('id', new_id);
});
That's just to start you out with. Go with a more advanced regex to futureproof.
精彩评论