jQuery:如何通过 src 查找图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/835378/
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
jQuery: How to find an image by its src
提问by kjgilla
I need to find an img by name and src. I have been trying the following to no avail.
我需要按名称和 src 查找 img。我一直在尝试以下无济于事。
var s = $("img[src='/images/greendot.gif'][name='BS']");
The html:
html:
<img alt="This item is active." name="BS" src="/images/greendot.gif"/>
vs
对比
<img alt="This item is not active." name="BS" src="/images/spacer.gif"/>
回答by Jared
without seeing the html I would say check your path.
没有看到 html 我会说检查你的路径。
$("img[src$='greendot.gif'][name='BS']")
given the following HTML:
给定以下 HTML:
<img src="http://assets0.twitter.com/images/twitter_logo_header.png" name="logo" />
this jquery worked:
这个 jquery 有效:
var x = $("img[src$='twitter_logo_header.png'][name='logo']");
alert(x.attr("src"));
回答by karim79
Try losing the quotes:
尝试丢失引号:
var s = $("img[src=../../images/greendot.gif][name=BS]");
回答by Mike
Browsers add full path to src, href and similar attributes. So even though element is defined with relative path, in DOM 'src' attribute contains domain name and full path. Using [src$="..."] syntax or specifying full domain name seem to be only options for finding images by src with jQuery.
浏览器添加了 src、href 和类似属性的完整路径。因此,即使元素是用相对路径定义的,在 DOM 中的 'src' 属性包含域名和完整路径。使用 [src$="..."] 语法或指定完整域名似乎是使用 jQuery 通过 src 查找图像的唯一选项。
I might be wrong here. src property of image object reports full path, but the attribute should contain path as specified in the code. [src="relative/path"] works in the latest jQuery version, maybe it was an early version where it didn't work.
我可能在这里错了。图像对象的 src 属性报告完整路径,但该属性应包含代码中指定的路径。[src="relative/path"] 在最新的 jQuery 版本中有效,也许它是早期版本,它不起作用。
回答by Turik
Change your img tag like this:
像这样更改你的 img 标签:
<img src="path/to/imgage/img.jpg" title="img.jpg" />
I mean add to your images title attribute and set them name of file.
我的意思是添加到您的图像标题属性并设置它们的文件名。
When you need to access sertain image you can do it as below:
当您需要访问sertain图像时,您可以按如下方式进行:
//Finding image that you need using 'title' attribute;
var imageTag = $("img[title='imageName']");
//Then if you need to do something with it;
imageTag.attr('src', 'path/to/newImage/newImage.jgp');
imageTag.attr('title', 'newImage.jpg');