[英]Why does my phone number href link redirect to 'About:Blank' address and how do I fix the issues?
[英]How do I add a dynamic phone number to the HTML5 phone number link href attribute?
對於我網站上的電話號碼,我有以下 HTML:
<span class="rTapNumber"></span>
這里的類激活一個腳本,並在跨度內插入一個隨機數(用於跟蹤目的。
我想使用移動電話鏈接,即<a href="tel:01234567890">
但號碼不能硬編碼......我怎樣才能獲得<span>
使用的動態號碼進入這個href
屬性?
生成的代碼應該是這樣的:
<span class="rTapNumber"><a href="tel:+441234567890">01234567890</a></span>
希望你能幫忙。
我使用了以下內容(rTapPostReplacement 函數是在替換所有數字后由 responsetap 調用的函數)。
function rTapPostReplacement() {
// loop through all links which are using the HTML5 href="tel:000000" property
$('a[href*="tel:"]').each(function(){
// get the replaced text/number
var number = $(this).text();
// replace all spaces with nothing (in case the tel: property doesn't like spaces)
number = number.replace(/\s+/g, '').toLowerCase();
// update the href attribute to the replaced number
$(this).attr('href', 'tel:' + number);
});
}
2016 年 4 月 6 日更新
我后來發現這個回調只會被調用一次(第一次發生 ResponseTap 替換)。 這是因為 ResponseTap 的默認實現僅替換屏幕上可見的數字。 無論出於何種原因,任何后續的數字替換都不會觸發回調。
因此,確保它可靠工作的唯一方法是修改 ResponseTap 跟蹤代碼,以便:
adiRVO = false; // This is set to true by default
無論可見性如何,這都會同時替換文檔中的所有數字。
所以完整的實現看起來像這樣
// The ResponseTap tracking code
var adiInit = "00000", adiRVO = false; // Set to false
var adiFunc = null;
(function() {
var adiSrc = document.createElement("script"); adiSrc.type = "text/javascript";
adiSrc.async = true;
adiSrc.src = ("https:" == document.location.protocol ? "https://static-ssl" : "http://static-cdn")
+ ".responsetap.com/static/scripts/rTapTrack.min.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(adiSrc, s);
})();
// The ResponseTap callback
function rTapPostReplacement() {
// loop through all links which are using the HTML5 href="tel:000000" property
$('a[href*="tel:"]').each(function(){
// get the replaced text/number
var number = $(this).text();
// replace all spaces with nothing (in case the tel: property doesn't like spaces)
number = number.replace(/\s+/g, '').toLowerCase();
// update the href attribute to the replaced number
$(this).attr('href', 'tel:' + number);
});
}
出於某種原因,盡管這個問題已經 6 歲了,但似乎仍然很熱門,所以這是我使用MutationObserver API 的解決方案
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', () => {
let observer = new MutationObserver(callback);
let observerOptions = {
childList: true,
attributes: false,
characterData: false,
subtree: false,
};
let node = document.getElementById('rTapNumber');
function callback(mutations) {
mutations.forEach(el => {
if(el.type === 'childList') {
document.querySelector('.responseTapLink').href = 'tel:' + el.target.innerText;
observer.disconnect();
}
});
}
observer.observe(node, observerOptions);
});
</script>
<a class="responseTapLink" href=""><span id="rTapNumber" class="rTapNumber00000">00000 000 000</span></a>
一般方法如下
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.