【问题标题】:Add an image id by finding the image alt通过查找图像 alt 添加图像 id
【发布时间】:2015-04-22 08:46:47
【问题描述】:

我无法手动访问以更改 html 的页面上没有 id 的图像。我希望能够在我有权访问的 javascript 文件中添加一个 id 值。

我找到了这个帖子:

Finding An image tag using the alt text

还有这个:

Replace image and image title/alt text with Javascript

我一直在尝试一些变体来让它发挥作用。

谁能告诉我哪里出错了?我目前正在使用:

$('img[alt="close_pop"]').attr('id','close');

我认为我没有完全理解,因为这是我认为它正在做的事情:

$('img[alt="close_pop"]') //getting the image based on the alt tag using jquery.

.attr('id','close'); //then I was applying a new id to that image. 

感谢所有帮助!

【问题讨论】:

  • 为什么您的解决方案不起作用?
  • id 没有像我想象的那样添加到 img 中
  • 你是如何测试id是否被添加的?
  • javascript 正在加载页面,所以我刷新页面并检查 id 是否已添加到图像中。我在那里有一个console.log,以确保它在加载时点击了javascript文件的那个位。
  • 你试过用 prop() 代替 attr() 吗?

标签: javascript jquery html image


【解决方案1】:

检查元素并搜索 id。它得到 alt 的值:

$(window).load(function() {
  var img = $('img[alt="test"]');
  var alt = img.attr('alt');
  console.log(alt);
  img.attr('id', alt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img alt="test" src="" />

【讨论】:

  • 解决了这个问题 - 谢谢!时间到时将标记为正确答案。
【解决方案2】:
<img src="smiley.gif" class="smile" id="smiley" alt="Smiley face" width="42" height="42">



 $(window).load(function(){
    $("img").click(function() {
        var img = $("img[alt='Smiley face']");
        img.attr("id", "fool");
        console.log(img.attr("id"));
    });
    });

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多