简体   繁体   English

jQuery用src选择img

[英]jQuery select img with src

I want to select an image (with jQuery) by the src attribute. 我想通过src属性选择一个图像(使用jQuery)。 The Image is inside an ul and a collection of div's. Image位于ul和div的集合中。 The id of the ul is "sortable". ul的id是“可排序的”。

Here is my HTML: 这是我的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: 这是我的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: 但如果我像这样写js:

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

so they find the image. 所以他们找到了图像。

I'm not sure why the difference, but try using the $= attribute ends with selector. 我不确定为什么会有区别,但尝试使用$=属性以选择器结束

Seems to work. 似乎工作。

Example: http://jsfiddle.net/bTf7K/ 示例: 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. 编辑:差异可能与获取jQuery在不同时间使用的属性值的方法有关。

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. 所以我猜jQuery在不同的时间使用这两种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM