【问题标题】:Get the first src of an image element获取图像元素的第一个 src
【发布时间】:2018-05-28 18:29:53
【问题描述】:

我正在尝试在 giphy 链接中获取 img 元素的第一个 src,如下所示: https://media.giphy.com/media/4uZv6yO0loMKc/giphy.gif

我正在使用这个 jquery 代码:

$('img').attr('src');

但它会获得以 .gif 结尾的第二个源链接,而不是以 .webp 结尾的源链接。

如何获取特定的 img src 链接,即以 .webp 结尾的链接?

【问题讨论】:

标签: javascript jquery windows google-chrome


【解决方案1】:

你可以像$("img[src$='gif']:first").attr("src")一样使用[src$='gif']

[src$='gif'] 将选择一个或多个srcgif 结尾的元素

这也更安全,因此您不必担心图像的顺序

演示

console.log($("img[src$='gif']:first").attr("src"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://media.giphy.com/media/4uZv6yO0loMKc/giphy.gif" />

【讨论】:

    【解决方案2】:

    在该页面打开时在console 中执行此代码会给我正确的图像。

    document.querySelectorAll('img')[0].src
    

    所以这个也可以

    document.querySelector('img').src
    

    【讨论】:

      【解决方案3】:

      在 JavaScript 中: var attribute = document.getElementsByTagName('img')[0].attributes.src.value;

      您的问题不是 jquery 选择不同的属性。 src 属性是一个对象,具有不同的属性。选择“值”属性将返回以.webp 结尾的链接,就像您的目标一样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 2015-01-19
        • 1970-01-01
        • 2022-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多