jQuery用src选择img [英] jQuery select img with src

查看:467
本文介绍了jQuery用src选择img的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的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>

等。

这是我的js:

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

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

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');
}

所以他们找到了图片。

推荐答案

我不确定为什么会有区别,但尝试使用 $ = 属性以选择器结束。

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

似乎工作。

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

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






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


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

使用本机方法:

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

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

所以我猜jQuery你在不同的时间选择这两个。

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

这篇关于jQuery用src选择img的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆