[英]Can't capitalize first letter, element not updated
我从这样的文本框中获取字符串(在索引递增的循环中):
var name = document.getElementById("TextBox" + index).value;
我的脚本中有一个函数,看起来像是大写第一个字母:
function capital(string)
{
return string.charAt(0).toUpperCase() + string.slice(1);
}
并尝试像这样使用它:
var name = document.getElementById("TextBox" + index).value;
capital(name);
它们在同一script
标签中具有不同的功能。 我要去哪里错了?
确保将修改后的值分配回控件:
var element = document.getElementById("TextBox" + index);
var name = element.value;
element.value = capital(name);
字符串在js中是不可变的,您需要重新分配。
var name = capital(document.getElementById("TextBox" + index).value);
加号字符串按值传递,因此它们被复制到新函数中。 因此,无论您对函数执行什么操作,都不会对您的name变量造成任何影响。
您是否正在尝试使用输入类型获取getElementById,还是在文本框上拥有名为“ TextBox”的实际ID? 以下工作正常, 请参阅小提琴
var index = 1;
var name = document.getElementById("test" + index).value;
function capital(str)
{
return str.charAt(0).toUpperCase() + str.slice(1);
}
alert(capital(name));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.