开发者

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 variable.

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.

  1. The selector gets us all the images with their src tags having a "/".
  2. Filtering the images that have "thread_" after the last "/"
  3. Taking the last image of all such images
  4. 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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜