【问题标题】:Getting the source of a specific image element with jQuery使用 jQuery 获取特定图像元素的来源
【发布时间】:2012-05-22 20:29:59
【问题描述】:

我有许多图像元素,并且想要获取替代文本为 "example" 的特定图像的来源。

我试过了:

var src = $('.conversation_img').attr('src');

但我找不到我需要的那个。

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

【问题讨论】:

  • 您收到任何错误消息。?
  • 没有我得到第一个元素我不知道元素位置我只知道替代文本
  • 在这里工作的人演示 :) - jsfiddle.net/yL5cf/1

标签: jquery jquery-selectors


【解决方案1】:

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

var src = $('.conversation_img[alt="example"]').attr('src');

请参考jQuery Documentation 属性等于选择器

请参考Demo中的例子

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

HTML

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

</div>

脚本查询

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

输出将是

两个警报消息,每个都有值

  1. 带有替代文本的图像来源 = 示例 - \images\show.jpg
  2. 带有替代文本的图像来源 = exampleAll - \images\showAll.jpg

【讨论】:

  • 应该是这个兄弟:var src = $('img.conversation_img[alt="example"]').attr('src'); 因为单引号内的单引号不起作用,cheerios!
  • 你没有转义 example 并且会出现错误
【解决方案2】:
$('img.conversation_img[alt="example"]')
    .each(function(){
         alert($(this).attr('src'))
    });

这将显示 alt='example' 类“conversation_img”的所有图像的 src 属性

【讨论】:

    【解决方案3】:
    var src = $('img.conversation_img[alt="example"]').attr('src');
    

    如果您有多个匹配元素,则只会返回第一个的 src。

    【讨论】:

      【解决方案4】:

      如果您不是特别需要图像的替代文本,那么您可以只定位图像的类/ID。

      $('img.propImg').each(function(){ 
           enter code here
      }
      

      我知道它并没有完全回答这个问题,尽管我花了很长时间试图弄清楚这一点,而这个问题给了我解决方案:)。就我而言,我需要隐藏任何带有特定 src 的图像标签。

      $('img.propImg').each(function(){ //for each loop that gets all the images. 
              if($(this).attr('src') == "img/{{images}}") { // if the src matches this
              $(this).css("display", "none") // hide the image.
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-10
        • 2018-03-17
        相关资源
        最近更新 更多