【发布时间】:2015-09-04 18:19:46
【问题描述】:
如果,在 onclick 的一个函数中,我说:
offset=parseFloat(document.getElementById("offsetId").value); //value=-2
center=sp+offset; // sp is a float == 190
alert("center="+center);
我得到“center=190[object HTMLInputElement]”
如果我将函数分隔为:
offset=document.getElementById("offsetId");
offset=parseFloat(offset.value);
center=sp+offset;
alert("center="+center);
我得到同样的错误。
但如果我这样做
offset=document.getElementById("offsetId");
center=sp+parseFloat(offset.value);
alert("center="+center);
我得到正确答案,center=188。
为什么我不能像前两个示例那样连接函数? 他们看起来和我一模一样。
编辑: 这是产生“不可能”结果的示例代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
</head>
<body>
<script>sp=parseFloat(190.); </script>
<!-- same result with sp=190.; sp=Number(190.); sp=Number("190."); -->
<form>
<p>Enter Offset <input id="offsetId" type="text" name="offset" value=0> <!-- eg -2 -->
<p>
<input
type="button"
name="go"
value="Do the Plot"
onclick='
alert("at19: sp = "+sp+", typeof sp=", typeof sp);
// shows: at19: sp = 190, typeof sp=
offset=parseFloat(document.getElementById("offsetId").value);
alert("at22, offset="+offset+", typeof offset="+typeof offset);
// shows: at23, offset=[object HTMLInputElement], typeof offset=object
center=sp+offset;
alert("at25: center="+center);
// shows: at24: center=190[object HTMLInputElement]
// alternate 1
offset = parseFloat(offset.value);
center=sp+offset;
alert("at31: offset="+offset+", center="+center);
// shows: at31: offset=[object HTMLInputElement], center=190[object HTMLInputElement]
// alternate 2
offset=document.getElementById("offsetId");
center=sp+parseFloat(offset.value);
alert("at37: offset="+offset+", center="+center);
// shows: at36: offset=[object HTMLInputElement], center=188
'
>
</form>
</body>
</html>
请注意,最后一种方法给出了正确答案。 我怀疑我无法让 sp 显示一个类型可能很重要。
【问题讨论】:
-
我举了一个例子(现在是一个完整的程序),它给出的输出非常不寻常,以至于你声称这是不可能的,你认为它不值得发布吗?请查看我发布的程序,以及“不可能”的警报输出。
-
您有责任提供重现问题的代码,而您曾未能做到这一点。现在您已经生成了确实重现问题的代码,问题和解决方案就很明显了。
标签: javascript input syntax