[英]JavaScript toUpperCase() not working
我正在尝试制作一个小的脚本,确定输入的文本是完全大写,完全小写还是都不是。 这里:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script>
function caps (p1){
console.log ("yes");
if (p1.toUpperCase() == p1){
alert ("Is uppercase")
}
else if (p1.toLowerCase() == p1){
alert ("Is lowercase")
}
else {
alert ("Is mix of both");
}
}
</script>
<form id="form1" name="form1" method="post" action="">
<p>
<label>Write something<br />
<input type="text" name="numero" id="numero" />
</label>
</p>
<p>
<input onclick="caps(numero)" type="submit" name="button" id="button" value="Submit" />
</p>
</form>
</body>
</html>
但是,它不起作用。 Firefox Web Console坚持认为“ toUpperCase()”不是有效方法。 这里发生了什么事?
在onclick
,您可以这样调用函数: caps(numero)
这没有将numero
作为String
传递。 它通过它作为变量名。 一个未定义的。 .toUpperCase
是String
上的方法,在undefined
上将不存在。
而是尝试: caps('numero')
或者,如果您尝试传递文本输入的值 :
caps(document.getElementById('numero').value)
也许更好,将其内置到您的函数中:
function caps (id) {
var p1 = document.getElementById(id).value
if (p1.toUpperCase() == p1){
alert ("Is uppercase")
}
else if (p1.toLowerCase() == p1){
alert ("Is lowercase")
}
else {
alert ("Is mix of both");
}
}
这样,您可以像onclick="caps('numero')"
一样调用它,将您想要输入其值的输入的id
传递给UpperCase
尝试这种方式,p1是输入元素而不是输入元素的值,因此请与p1.value进行比较
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function caps (p1)
{
console.log (p1); //see here
console.log (p1.value);
if (p1.value.toUpperCase() == p1.value){
alert ("Is uppercase")
}
else if (p1.value.toLowerCase() == p1.value){
alert ("Is lowercase")
}
else {
alert ("Is mix of both");
}
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label>Write something<br />
<input type="text" name="numero" id="numero" />
</label>
</p>
<p>
<input onclick="caps(numero)" type="submit" name="button" id="button" value="Submit" />
</p>
</form>
</body>
</html>
不是p1.toUpperCase() == p1
,p1代表input
dom元素,其中id =“ p1”,
没有touppercase
方法,只有string有此方法,因此您应该使用p1.value
document.getElementById(p1)
等于p1
, p1
是id名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.