我正在使用WordPress主题,这是我试图实现的功能:
<a href="tel:225-1077">225-1077</a>
HTML确实很容易做到,但我真的不擅长WordPress,我得到的这个主题有太多文件,很难找到我应该编辑的地方。然而,这个主题允许你添加自定义JS,所以我想知道上面的功能是否可以用JS完成。
非常感谢您的帮助!
很简单,这是可能的,但这并不意味着这是一个好主意。跨手机的JS支持并不一致,甚至不总是启用,这意味着这些人永远不会看到你的链接。
使用JS创建链接很简单:
var cta = document.createElement('a');
cta.href = 'tel:12341234';
cta.setAttribute('class', 'my cta classes');
cta.appendChild(document.createTextNode('1234-1234'));
然后你需要把它放在页面的某个地方。如果我们有一个特定类的<div>
,我们可以使用它:
这是我们的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>