最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery find element by src attribute - Stack Overflow

programmeradmin1浏览0评论

I have this small gallery (the code is just example):

<div id="gallery_imgs">
    <img src=".png" />
    <img src=".png" />
    <img src=".png" />
</div>
<p></p>

JS code:

var that = $("#gallery_imgs img:eq(1)");
$("p").html($("#gallery_imgs img").find("[src='"+that.attr("src")+"']").length);

This return 0. Any idea why? Is this a bug, or what am I doing wrong?

I have this small gallery (the code is just example):

<div id="gallery_imgs">
    <img src="http://fc01.deviantart/fs71/f/2014/112/0/9/nobody_believes_in_me_by_idjpanda-d7fkd7m.png" />
    <img src="http://fc09.deviantart/fs71/f/2014/112/5/6/feed_me_d__by_idjpanda-d7fgids.png" />
    <img src="http://fc02.deviantart/fs71/f/2014/104/e/5/blar_auction_by_idjpanda-d7ehmoc.png" />
</div>
<p></p>

JS code:

var that = $("#gallery_imgs img:eq(1)");
$("p").html($("#gallery_imgs img").find("[src='"+that.attr("src")+"']").length);

This return 0. Any idea why? Is this a bug, or what am I doing wrong?

Share Improve this question asked Apr 23, 2014 at 16:19 kleniumklenium 2,6272 gold badges27 silver badges52 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You need .filter()

$("p").html($("#gallery_imgs img").filter("[src='"+that.attr("src")+"']").length);

you can use .find() this way

$("p").html($("#gallery_imgs").find("img [src='"+that.attr("src")+"']").length);

Problem

$("#gallery_imgs img").find("[src='"+that.attr("src")+"']") you are trying to find the element with src inside the img element not within in the img element

Try

$("p").html($("#gallery_imgs img[src="+that.attr("src")+"]").length);
发布评论

评论列表(0)

  1. 暂无评论