[英]Javascript - I can't concatenate at the beginning of my string
Here's what I want to do: 这是我想做的:
Check if there is the first character "@" within my string, If not, add it. 检查我的字符串中是否有第一个字符“ @”,如果没有,请添加它。
Here is my code: 这是我的代码:
$(document).ready(function(){
$("#twitter").blur(function() {
var s = $("#twitter").val();
alert(s);
var isAt = s.charAt(0);
alert(isAt);
if(isAt !== "@") {
alert("lol");
s = "@" + s;
}
});
});
The Problem: 问题:
When I tab to the next input (in turn blurring #twitter) Its lol'ing but not setting the value of the input to "@Rick" when I type "Rick". 当我切换到下一个输入时(依次模糊#twitter),当我键入“ Rick”时,它会哈哈但没有将输入的值设置为“ @Rick”。
Any ideas why? 有什么想法吗?
Change this: 更改此:
s = "@" + s;
to this: 对此:
$("#twitter").val('@' + s);
The problem is that you're updating the value stored in your s
reference, but there's no dynamic binding between that variable and the input field itself (ie, you have to still update the #twitter
value manually). 问题在于您正在更新存储在
s
引用中的值,但是该变量与输入字段本身之间没有动态绑定(即,您仍然#twitter
手动更新#twitter
值)。
Edit: as suggested by @epascarello below, this is probably a cleaner solution: 编辑:如下@epascarello所建议,这可能是一种更清洁的解决方案:
$(document).ready(function(){
$('#twitter').blur(function() {
var $this = $(this),
val = $this.val();
if (val.charAt(0) !== '@') {
$this.val('@' + val);
}
});
});
And... just for the heck of it, another approach: 还有...只是为了它,另一种方法是:
$(document).ready(function(){
$('#twitter').blur(function() {
if (this.value.charAt(0) === '@') return;
$(this).val(function(i, v) { return '@' + v });
});
});
One more... 多一个...
$(document).on('blur', '#twitter', function() {
$(this).val(function(i, v) {
return v.replace(/(@)?(.*)/, '@$2')
});
});
Note: you should probably use the first or second one... i'm getting esoteric over here... 注意:您可能应该使用第一个或第二个...我在这里变得很深奥...
$(document).ready(function(){
$("#twitter").blur(function() {
var s = $("#twitter").val();
alert(s);
var isAt = s.charAt(0);
alert(isAt);
if(isAt !== "@") {
alert("lol");
$("#twitter").val("@" + s);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.