You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript为WordPress主题中的图片添加aria-label?

问题:为WordPress面板中的图片添加aria-label失败

我用WordPress主题构建器创建了若干包含图片和文本的面板,但该主题的构建工具无法为图片添加aria-label。尝试用JavaScript实现此功能但未成功,以下是相关代码:

HTML代码

<div class="module module-link-block tb_c1o1565 icon-center solid licences-permits" data-lazy="1">
  <a href="#" title="Licences &amp; Permits" class="tb_link_block_container ui tb_default_color">
    <img loading="lazy" width="66" height="66" decoding="async" class="tf_vmiddle tf_box tb_link_block_img" src="https://xxxxx.xxxxx.xxxxxx.net/wp-content/uploads/2024/04/licence-1.svg">
    <div class="tf-lb-content">
      <div class="tb_link_block_heading">Licences & Permits</div>
      <div class="tb_link_block_blurb">Browse Licenses & Permits</div>
    </div>
  </a>
</div>

当前无效的jQuery代码

jQuery(function($) { 
  jQuery('.licences-permits').attr('aria-label','Licences &amp; Permits'); 
}); 

解决方案

你的代码核心问题是选择器错误:当前是给外层的div.licences-permits添加aria-label,但实际需要给该div内部的图片元素设置属性。

方案1:直接选择目标图片(DOM加载完成后图片已存在)

修正选择器,直接定位到图片元素:

jQuery(function($) {
  // 定位到.licences-permits容器下的图片,设置aria-label
  $('.licences-permits .tb_link_block_img').attr('aria-label', 'Licences & Permits');
});

方案2:适配懒加载场景(图片动态插入DOM)

如果图片是懒加载动态添加的,DOM就绪时可能还未渲染,可使用MutationObserver监听元素变化,确保图片出现后再设置属性:

jQuery(function($) {
  const targetContainer = document.querySelector('.licences-permits');
  if (!targetContainer) return;

  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.addedNodes.length) {
        const targetImg = targetContainer.querySelector('.tb_link_block_img');
        if (targetImg) {
          targetImg.setAttribute('aria-label', 'Licences & Permits');
          observer.disconnect(); // 设置完成后停止监听,避免重复执行
        }
      }
    });
  });

  // 监听目标容器的子元素变化
  observer.observe(targetContainer, { childList: true, subtree: true });
});

内容的提问来源于stack exchange,提问作者Mickey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:10:12