jQuery wildcard character in image source
I would like to change the src attribute of an image on click using jQuery. Here's the HTML:
<a href="#" class="view2">View 2</a>
<img src="images/shoe1a.jpg" class="sb-player" />
And in the img src, I want to replace the "a" to a "b," but my problem is that I wan开发者_StackOverflow中文版t to ignore the "1" that's in front of it, since it could look like this as well:
<img src="images/shoe2a.jpg" class="sb-player" />
I got this far with my jQuery, and the asterisk is where I need a wildcard character:
$(function() {
$('.view2').click(function() {
$('.sb-player').attr('src', 'images/shoe'+*+'b.jpg');
return false;
});
});
Is there a certain character that could be a wildcard for any number?
Just .replace()
the entire end of the src
string, replacing a.jpg
with b.jpg
.
You can pass a function to .attr()
.
The parameter i
represents the current iteration in the set, and val
is the current value. The return value represents the new value.
$(function() {
$('.view2').click(function() {
$('.sb-player').attr('src', function(i,val) {
return val.replace('a.jpg','b.jpg');
});
return false;
});
});
The most powerful way to match any part of a string is using Regular Expressions in javascript.
Maybe in this way you can solve your problem:
$(function() {
$('.view2').click(function() {
var originalSrc = $('.sb-player').attr('src');
$('.sb-player').attr('src', originalSrc.replace(/a\./,"b."));
return false;
});
});
精彩评论