是否可以给 href="mailto:" 数据绑定的值:文本?
Is it possible give an href="mailto:" the value of a data-bind: text?
我正在尝试将 data-bind: text 函数的值赋予 href="mailto:" 但似乎无法正确处理。
我目前的代码:
HTML:
<a href="#" class="mailCloseBranch" data-bind="text: closestBranch().email">someEmailFromDataBind.com
</a>
替换 href 的值:
$("a.mailCloseBranch[href$='#']").each(function() {
var ref = document.getElementsByClassName('mailCloseBranch')[0].value;
var mailref = 'mailto:' + String(ref);
this.href = this.href.replace("#", mailref);
});
来自 var mailref 的 'mailto:' 字符串被插入并且正确的电子邮件显示在
<a>
元素
但是 var ref 的值保持未定义,这反过来导致没有 link 到“mailto”。
也许这些可以提供一些见解?
在绑定函数中,您可以使用 this
直接访问超链接,从而访问它的属性,而不是使用 document.getElementsByClassName('mailCloseBranch')[0].value
(这是错误的)或 document.getElementsByClassName('mailCloseBranch')[0].textContent
// using the LINK TEXT to form part of the new href
$("a.mailCloseBranch[href$='#']").each( function() {
this.href = this.href.replace("#", 'mailto:' + String( this.textContent ) );
});
// using the DATA.BIND attribute value to form part of the new href
$("a.mailCloseBranch-2[href$='#']").each( function() {
this.href = this.href.replace("#", 'mailto:' + String( this.dataset.bind.replace('text:','') ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="mailCloseBranch" data-bind="text:closestBranch().email">someEmailTextcontent.com</a> |
<a href="#" class="mailCloseBranch-2" data-bind="text:closestBranch().email">emailfromDataBind.com</a>
我的问题的解决方案:
data binding email into mailto link json
我正在尝试将 data-bind: text 函数的值赋予 href="mailto:" 但似乎无法正确处理。
我目前的代码:
HTML:
<a href="#" class="mailCloseBranch" data-bind="text: closestBranch().email">someEmailFromDataBind.com
</a>
替换 href 的值:
$("a.mailCloseBranch[href$='#']").each(function() {
var ref = document.getElementsByClassName('mailCloseBranch')[0].value;
var mailref = 'mailto:' + String(ref);
this.href = this.href.replace("#", mailref);
});
来自 var mailref 的 'mailto:' 字符串被插入并且正确的电子邮件显示在
<a>
元素
但是 var ref 的值保持未定义,这反过来导致没有 link 到“mailto”。
也许这些可以提供一些见解?
在绑定函数中,您可以使用 this
直接访问超链接,从而访问它的属性,而不是使用 document.getElementsByClassName('mailCloseBranch')[0].value
(这是错误的)或 document.getElementsByClassName('mailCloseBranch')[0].textContent
// using the LINK TEXT to form part of the new href
$("a.mailCloseBranch[href$='#']").each( function() {
this.href = this.href.replace("#", 'mailto:' + String( this.textContent ) );
});
// using the DATA.BIND attribute value to form part of the new href
$("a.mailCloseBranch-2[href$='#']").each( function() {
this.href = this.href.replace("#", 'mailto:' + String( this.dataset.bind.replace('text:','') ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="mailCloseBranch" data-bind="text:closestBranch().email">someEmailTextcontent.com</a> |
<a href="#" class="mailCloseBranch-2" data-bind="text:closestBranch().email">emailfromDataBind.com</a>
我的问题的解决方案:
data binding email into mailto link json