如何使用 Jquery 动态更改类似 class 中图像的 alt 标签?

how to alter alt tag of images inside a similar class dynamically using Jquery?

所以用例是这样的,我有一个块,我在其中打印具有相似内容的相似内容中的图像 class 现在我想通过在末尾添加书籍封面来更改 alt 但是当我 运行 代码书封面渲染了不止一次,我有办法解决这个问题吗?

/* changing alt tags of featured items */
    $(".featured-item").each( function () {
       var alt_val = $(this).find('img').attr("alt");
       console.log(alt_val);
       $(this).find('img').attr("alt", "Book cover:"+alt_val+"");
    });
  • 下次使用时使用一个变量(我)。

  • 在完成你的 alt 属性后添加一个 class "done-with-alt"。如果元素有 class "done-with-alt" continue.

检查并跳过: if ($(this).hasClass("done-with-alt")) return true;

完成后: $(this).addClass("done-with-alt");

您的新代码可以是:

/* changing alt tags of featured items */
    $(".featured-item").each( function () {
       var me = $(this);
       if (me.hasClass("done-with-alt")) return true;

       
       var alt_val = me.find('img').attr("alt");
       console.log(alt_val);
       me.find('img').attr("alt", "Book cover:"+alt_val+"");
     
       me.addClass("done-with-alt");
    });

如果 jQuery 无法更新您的元素 (.featured-item),您可以环绕此间隔并检查每 100 毫秒是否持续大约 1000 毫秒:

var myInterval = setInterval(function(){

    /* changing alt tags of featured items */
    $(".featured-item").each( function () {
       var me = $(this);
       if (me.hasClass("done-with-alt")) return true;

       
       var alt_val = me.find('img').attr("alt");
       console.log(alt_val);
       me.find('img').attr("alt", "Book cover:"+alt_val+"");
     
       me.addClass("done-with-alt");
    });
},100);

setTimeout(function(){
    clearInterval(myInterval);
},1000);

不是好的代码,因为 interval/checks 必须停止。所以这段代码使用触发超时来清除间隔(希望在 1000 毫秒后完成)。