selecting a char in jquery
I got a question,
<a id="shoppingLink1" href="?page=bestellen&action=add&i开发者_如何学JAVAd=2">
<img src="images/shoppingcartButton.png" class="shoppingButton" alt="shoppingcartButton" title="shoppingcartButton"/>
</a><br/>
in jquery, when i click on the shoppingButton i would like to select the last character from the id "shoppingLink". the "1" .
These are dynamicly added thou so if it comes to 10 it should automaticly select the last 2 characters. Anyone who can help me?
$('.shoppingButton').click(function () {
var id = parseInt($(this).parent('a[id^=shoppingLink]').attr('id').match(/\d+$/)[0], 10);
// Do stuff.
return false;
});
This uses RegExp to match all digits at the end of $(this).parent('a[id^=shoppingLink]').attr('id')
(i.e. the .shoppingButton
's parent a
's id
attribute where the id
begins with "shoppingLink"
). It then parses these digits into a number with parseInt
.
Why don't you call it shopping-link-1
or something similar, and put the shoppingButton
class on the a
tag instead of img
? That way you can use the split
method to get the numeric ID. Here's some example jQuery to use:
$('a.shoppingButton').click(function() {
var link_id = parseInt($(this).attr('id').split('-')[2]);
// do your thing with link_id here
});
That way, when you split by the '-'
character, it's guaranteed to just return the number no matter how many digits it has. But if you absolutely need to keep the current markup, use a regular expression:
$('img.shoppingButton').click(function() {
var link_id = parseInt($(this).parent().attr('id').match(/(\d+)$/)[1]);
// do your thing with link_id here
});
That way it will respond to clicks on the image, and still pull the ID from the a
tag.
You could look at it the other way round: you know to expect the string 'shoppingLink' so strip that off first then parse the number:
$('a.shoppingButton').click(function() {
var theID = parseInt($(this).attr('id').replace('shoppingButton', ''));
theID = isNaN(theID) ? 0 : theID;
// actions here
});
精彩评论