使用jQuery获取特定图像元素的源代码

Ira*_*ili 27 jquery jquery-selectors

我有很多图像元素,并希望获得特定图像的来源,其中替代文本是"示例".

我试过这个:

var src = $('.conversation_img').attr('src');
Run Code Online (Sandbox Code Playgroud)

但我不能得到那个我需要的那个.

如何根据其替代文本选择特定图像元素?

Mur*_*aza 55

要选择只知道属性值的元素,可以使用下面的jQuery脚本

var src = $('.conversation_img[alt="example"]').attr('src');
Run Code Online (Sandbox Code Playgroud)

请参阅jQuery文档以获取属性等于选择器

另请参阅演示中的示例

以下是您无法访问演示的代码..

HTML

<div>
    <img alt="example" src="\images\show.jpg" />
    <img  alt="exampleAll" src="\images\showAll.jpg" />  

</div>
Run Code Online (Sandbox Code Playgroud)

SCRIPT JQUERY

var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);


var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );
Run Code Online (Sandbox Code Playgroud)

输出将是

两条警报消息各有值

  1. 替代文字的图像来源=例子 - \images\show.jpg
  2. 替代文字的图像来源= exampleAll - \images\showAll.jpg


str*_*rah 7

$('img.conversation_img[alt="example"]')
    .each(function(){
         alert($(this).attr('src'))
    });
Run Code Online (Sandbox Code Playgroud)

这将显示类'conversation_img'的所有图像的src属性,其中alt ='example'