在输入类型的电子邮件中,我尝试在键入@字符后立即添加域名。 例如,如果用户输入john.doe @,我尝试添加yourdomain.com。 我已经编写了以下代码,但是当它运行时,它将显示john.doe@yourdomain.com @。
如何摆脱最后一个@字符?
$(document).on('keypress', 'input#email', function(e) {
console.log('keypress champ mail');
if (e.which !== 64) {
console.log("Charcter was typed. It was: " + String.fromCharCode(e.which));
console.log(this.value);
} else {
var c = String.fromCharCode(e.which);
//process the single character or
var textValue = this.value;
var fulltext = textValue + c + "yourdomain.com";
console.log(fulltext);
this.value = "";
this.value = fulltext;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email">
答案 0 :(得分:4)
要实现所需的功能,您需要在按下preventDefault()
键时在keypress
事件上调用@
。另外请注意,您可以整理逻辑。试试这个:
$(document).on('keypress', 'input#email', function(e) {
if (e.which == 64) {
e.preventDefault();
var c = String.fromCharCode(e.which);
this.value = this.value + c + "yourdomain.com";
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="email" />
也可能会说var c = String.fromCharCode(e.which);
行是多余的,因为它总是({em> )是'@'
,但我将由您决定。