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

如何使用.each函数让JS代码适配页面所有#tel元素

问题根因

HTML 规范要求同一页面内的 ID 必须全局唯一,因此document.getElementById('tel')永远只会返回页面中第一个匹配 ID 的元素,这是原有代码仅对第一个按钮生效的核心原因。你之前调用.each方法未生效,也是因为 ID 选择器只能匹配到单个元素。

修复方案

1. 调整HTML属性(推荐)

将所有电话按钮的id="tel"改为添加tel类名,避免重复 ID 违反标准,修改后的 HTML 片段参考:

<div class="elementor-button-wrapper">
    <a href="http://44400907" class="elementor-button-link elementor-button elementor-size-xs tel" role="button">
        <span class="elementor-button-content-wrapper">
            <span class="elementor-button-text elementor-inline-editing" data-elementor-setting-key="text" data-elementor-inline-editing-toolbar="none">
                44 40 09 07
            </span>
        </span>
    </a>
</div>

2. 替换JS代码

原生JS实现(无需依赖jQuery)

// 选中所有带tel类的链接
const telLinks = document.querySelectorAll('.tel');
telLinks.forEach(link => {
  const originalHref = link.getAttribute('href');
  // 跳过href为空的元素避免报错
  if (!originalHref) return;
  link.setAttribute('href', originalHref.replace('http://', 'tel:'));
});

jQuery + .each实现

如果你页面已引入jQuery,想用.each方法可以用以下代码:

$('.tel').each(function() {
  const originalHref = $(this).attr('href');
  if (!originalHref) return;
  $(this).attr('href', originalHref.replace('http://', 'tel:'));
});

临时兼容方案(无法修改HTML移除重复ID时用)

如果受ACF配置限制无法修改重复ID属性,可以用属性选择器匹配所有id为tel的元素:

// 原生JS版本
document.querySelectorAll('[id="tel"]').forEach(link => {
  const originalHref = link.getAttribute('href');
  if (!originalHref) return;
  link.setAttribute('href', originalHref.replace('http://', 'tel:'));
});

// jQuery版本
$('[id="tel"]').each(function() {
  const originalHref = $(this).attr('href');
  if (!originalHref) return;
  $(this).attr('href', originalHref.replace('http://', 'tel:'));
});

*小提示:如果你的链接可能出现https://开头的情况,可以把替换规则改为正则匹配originalHref.replace(/^https?:\/\//, 'tel:'),同时兼容http和https两种协议。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 03:27:03