动态添加& lt; wbr& gt;标点之前的标签 [英] Dynamically add <wbr> tag before punctuation
问题描述
我正在尝试弄清楚如何使用jQuery动态地在电子邮件地址中标点之前添加<wbr>
标记.
I'm trying to figure out how to add a <wbr>
tag before punctuation in an email address, dynamically using jQuery.
我想象必须有一种方法来扫描字符串中的.".或"@"符号,然后将此标签放在它的前面,但我一直无法弄清楚.
I imagine there must be a way to scan the string for a "." or "@" sign and place this tag right before it, but I haven't been able to figure it out.
我尝试了两种不同的方法,这是我在寻找解决方案后能够提出的唯一解决方案:
I've attempted two different methods which were the only solutions I was able to come up with after searching for solutions:
HTML:
<div class="container">
<span class="some-special-classname">
verylongfirstname.verylonglastname@prettylongemailaddress.com
</span>
<br /> <br />
<button class="test">Test Button</button>
</div>
CSS
wbr:after {
content:"\00200B";
}
.container {
margin: 0 auto;
max-width: 400px;
padding : 10px;
border: 1px solid #bbb;
}
JavaScript :(第一次尝试)
$( ".test" ).click(function() {
$('.some-special-classname').html().replace(/@/g,"<wbr>@");
$('.some-special-classname').html().replace(/./g,"<wbr>.");
});
JavaScript :(第二次尝试)
var str = $('.some-special-classname').val();
str.replace(/@/g,'<wbr>@');
function myFunction() {
var str = $('.some-special-classname').val();
var n = str.indexOf(".");
document.getElementById("demo").innerHTML = n;
}
推荐答案
可以使用html(function(index, oldhtml)
解析和更新现有内容
Can use html(function(index, oldhtml)
to parse and update existing content
$('.some-special-classname').html(function(_, oldhtml){
return oldhtml.replace(/([@.])/g,"<wbr>$1");
});
如果选择器中有多个匹配元素,这还将遍历一个集合并将它们视为实例特定
This will also loop over a collection and treat them as instance specific if there are more than one matching elements in selector
参考: html(fn)文档
这篇关于动态添加& lt; wbr& gt;标点之前的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!