【问题标题】:How to implement telephone links with Javascript如何使用 Javascript 实现电话链接
【发布时间】:2015-01-04 04:13:05
【问题描述】:

我正在使用 WordPress 主题,这是我想要实现的功能:

<a href="tel:225-1077">225-1077</a>

它确实很容易用 HTML 完成,但我真的不擅长 WordPress,而且我得到的这个主题有很多文件,很难找到我应该编辑的地方,但是,这个主题允许你添加自定义 JS,所以我想知道上面的功能是否可以用 JS 完成。

非常感谢任何帮助!

【问题讨论】:

  • 有可能,但最好找到合适的文件并在HTML中完成,跨手机的JS支持并不完全一致。
  • @msturdy 如此真实。我正在尝试。该号码将遍布整个页面,它将充当 CTA 按钮,但它不会被带到某个地方,而是拨打指定的电话号码。

标签: javascript tel


【解决方案1】:

很简单,这是可能的,但这并不意味着这是一个好主意。跨手机的 JS 支持并不一致,甚至不总是启用,这意味着这些人永远不会看到你的链接。

用JS创建链接很简单:

var cta = document.createElement('a');

cta.href = 'tel:12341234';
cta.setAttribute('class', 'my cta classes');
cta.appendChild(document.createTextNode('1234-1234'));

然后你需要把它放在页面的某个地方。如果我们到处都有 &lt;div&gt;s 和一个特定的类,我们可以使用它:

这是我们的 HTML

<div class="target-cta">This div should receive a link</div>
<div class=""> this one shouldn't </div>
<div class="target-cta"> should have one here </div>
<div class=""> ...though not here</div>
<div class="target-cta">and finally, one here:</div>

我们插入链接的 JS 应该循环遍历这些元素,创建链接并在执行过程中插入它们:

var targets = document.getElementsByClassName('target-cta'),
    target, 
    i, 
    cta; // Call To Action

for (i = 0; i < targets.length; i++) {

    target = targets[i];
    cta = document.createElement('a');

    cta.href = 'tel:12341234';
    cta.setAttribute('class', 'my cta classes');
    cta.appendChild(document.createTextNode('1234-1234'));

    target.appendChild(cta);
};

    var targets = document.getElementsByClassName('target-cta'),
        target, i, cta;

    for (i = 0; i < targets.length; i++) {

        target = targets[i];
        cta = document.createElement('a');

        cta.href = 'tel:12341234';
        cta.setAttribute('class', 'my cta classes');
        cta.appendChild(document.createTextNode('1234-1234'));

        target.appendChild(cta);
    };
<div class="target-cta">This div should receive a link</div>
<div class=""> this one shouldn't </div>
<div class="target-cta"> should have one here </div>
<div class=""> ...though not here</div>
<div class="target-cta">and finally, one here:</div>

【讨论】:

  • 谢谢!这真的很有帮助。 :)
  • @CheeseCake 很高兴它有帮助! ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
  • 2012-05-23
  • 2012-12-17
  • 1970-01-01
相关资源
最近更新 更多