Javascript jQuery 使用 src 选择 img

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3752857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:00:12  来源:igfitidea点击:

jQuery select img with src

javascriptjquery

提问by Neoklosch

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

我想通过 src 属性选择一个图像(使用 jQuery)。图像位于 ul 和一组 div 中。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.

所以他们找到了图像。

回答by user113716

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

我不确定为什么会有差异,但尝试使用选择器结尾$=属性

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 在不同的时间使用这两个。