jQuery find img
<img src="http://site.com/some/category/thread_17.jpg" />
<img src="http://site.com/other/thread_17.jpg" />
How to find the last image on the page, that have "thread_
" after last "/
" in its src
attribute?
Script should throw src
to some var
iable.
Ajax is used to find the images on external page
$.ajaxQueue({
url: link,
type: 'GET',
success: function(data) {
var src = $('.slide img', data).attr('src'开发者_JAVA技巧);
}
});
It gives attribute of the last image from .slide
block.
Thanks.
$('.slide img[src*=\\/thread_]:last', data)
might do it
You can iterate through ALL of the images you have & perform regex on them, like this:
$('.slide img', data).each(function(index){
src = $(this).attr('src');
stringarray = src.split('/');
last_piece = stringarray[stringarray.length-1]
regexpatt = /thread_/
if ( regexpatt.test(last_piece) )
{
alert('we have a winner!');
}
else
{
alert('that was disappointing');
}
});
I am sure there is probably a more elegant way - you should probably search through the jquery docs for it, but this works... :)
var src = $(data).find('.slide img').last().attr('src');
You can use Regex in selectors
http://james.padolsey.com/javascript/regex-selector-for-jquery/
jQuery selector regular expressions
Hope this can help
Regargs.
Try the following.
var srcAttr = $('.slide img[src*=\/]', data).filter(function() {
var src = $(this).attr('src');
return src.substr(src.lastIndexOf("/")).indexOf('thread_') >= 0
}).last().attr('src');
Here I am doing the following things.
- The selector gets us all the images with their src tags having a "/".
- Filtering the images that have "thread_" after the last "/"
- Taking the last image of all such images
- Taking the src attribute of it.
Best guess, use a little .filter()
with a RegExp, and then the .last()
element in the set, grab its src using .attr('src')
var src = $('.slide img', data).filter(function() {
// only keep <img> whos src have '/thread_' without another '/' before the end
return $(this).attr('src').match(/\/thread_[^\/]*$/);
}).last().attr('src');
jsfiddle demo
精彩评论