开发者

how to retrieve the num value from image src?

I have a src information from a image like "/images/slide1.jpg" just I want to swap the slide1 to slide2, any one give开发者_如何转开发 me the right way to find and replace img src ?


document.getElementById('image id goes here').
    src = '/images/slide' + number + '.jpg';

If you want to get the number, then in your particular case, this would work:

number = document.getElementById('image id goes here').
    src.match(/\d+/)[0];


Here's an example for you using regex. It splits out the src into base, filename and extension (as well as picking up the last number in the filename as being the number you wish to increment)

var img = document.getElementById('myimage'),  // image element
    regex = /^(.+\/)([^\/]+)(\d+)(\..+)$/,     // parsing regex
    matches = regex.exec(img.src);             // execute regex

// Just to be tidy - getting the matches and parsing the number
var props = {
    'base' : matches[1],
    'filename' : matches[2],
    'filenumber' : parseInt(matches[3],10),
    'extension' : matches[4] 
};

// Create the next image string
var nextImage = props.base + props.filename + (props.filenumber+1) + props.extension; 

// Set the next image
img.src = nextImage;

alert('Set image to ' + nextImage);

Example: http://jsfiddle.net/jonathon/JKtXd/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜