jQuery用src选择img

Neo*_*sch 27 javascript jquery

我想通过src属性选择一个图像(使用jQuery).Image位于ul和div的集合中.ul的id是"可排序的".

这是我的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>
Run Code Online (Sandbox Code Playgroud)

等等

这是我的js:

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

我的问题是,他们没有找到任何图像.但如果我像这样写js:

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

所以他们找到了图像.

use*_*716 28

我不知道为什么会有差别,但尝试使用$=属性结尾选择.

似乎工作.

示例: http ://jsfiddle.net/bTf7K/

$('#sortable').find('img[src$="/test1.jpg"]')
Run Code Online (Sandbox Code Playgroud)

编辑:差异可能与获取jQuery在不同时间使用的属性值的方法有关.

使用本机方法:

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

element.src // returns the value but with the full domain path
Run Code Online (Sandbox Code Playgroud)

所以我猜jQuery在不同的时间使用这两种方法.

  • 已知错误!见http://forum.jquery.com/topic/src-attribute-selector-fails-on-img-tag-when-combined-with-a-direct-descendant-selector (2认同)