Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

javascript - jQuery select img with src

I want to select an image (with jQuery) by the src attribute. The Image is inside an ul and a collection of div's. The id of the ul is "sortable".

Here is my HTML:

<ul id="sortable">
  <li id="pic_0">
    <div class="sortEleWrapper">
      <div class="imgWrapper">
        <img src="/test1.jpg">
      </div>
      <input type="text" name="picText" id="picText" value="""" style="width:105px;color:#aaa" class="sortInput">
    </div>
    <input type="hidden" id="picSrc" name="picSrc" value="/test1.jpg">
  </li>
</ul>

etc.

and here is my js:

if($('#sortable').find('img[src="/test1.jpg"]').length > 0){
    alert('img exists');
}else{
    alert('img doesnt exists');
}

My problem is, that they don't find any image. But if I write the js like this:

if($('img[src="/test1.jpg"]').length > 0){
    alert('img exists');
}else{
    alert('img doesnt exists');
}

so they find the image.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure why the difference, but try using the $= attribute ends with selector.

Seems to work.

Example: http://jsfiddle.net/bTf7K/

$('#sortable').find('img[src$="/test1.jpg"]')

EDIT: The difference may have something to do with the method of getting the attribute value that jQuery uses at different times.

Using native methods:

element.getAttribute("src") // returns the actual value that was set

element.src // returns the value but with the full domain path

So I'm guessing jQuery uses both of these at different times.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...