1

我有一个简单的脚本,它将英寸的文本输入转换为厘米的另一个文本输入。但是,当我将它传递给我的函数时,我注意到我必须为传递给 document.getElementByID 的参数使用引号。我尝试了不带引号的 newheightcm ,但失败了。有没有办法避免这种情况以保持两个参数的一致性,即两者都有引号或都没有引号?

<script>
function inchestocm(IDin, IDcm) {   
    var inches = IDin.value;
    var centimeters = inches*2.54;  
    document.getElementById(IDcm).value = centimeters;  
}
</script>
<input type="text" id="newheight" onchange="inchestocm(newheight,'newheightcm')">
<input type="text" id="newheightcm">
4

4 回答 4

3

Because without the quotes you are looking for a variable newheight that is defined in the global scope. Some browsers do a bad thing and says if I do not have a variable with this id, I look for an DOM element that has that id.

So what you are passing in is an DOM Element with that id and not a string. That is why IDin.value works.

A better way of doing that is to pass in the scope of the element that was changed.

<input type="text" id="newheight" onchange="inchestocm(this,'newheightcm')">

That way you are not dealing with the browser quirk that made the code run in the first place.

于 2013-10-14T18:29:53.420 回答
0

您正在使用函数的参数,这就是您不能使用双引号的原因。如果您使用 id 的直接名称,则将使用双引号。

于 2013-10-14T18:43:33.443 回答
0
<input type="text" id="newheight" onchange="inchestocm(newheight,'newheightcm')">

在您的代码中,两个参数是不同的,第一个是您试图从中获取值的对象,第二个是您要粘贴结果的字符串。不确定,但试试这个。

<script>
function inchestocm(IDin, IDcm) {   
var inches = IDin.value;
var centimeters = inches*2.54;  
IDcm.value = centimeters;  
}
</script>
<input type="text" id="newheight" onchange="inchestocm(newheight,document.getElementById('newheightcm'))">
<input type="text" id="newheightcm">
于 2013-10-14T18:39:00.313 回答
0
函数inchestocm(IDin, IDcm) { var inches = IDin.value; var 厘米 = 英寸*2.54;document.getElementById(IDcm).value = 厘米;}

newheight是 DOM 元素<input type="text" id="newheight" onchange="inchestocm(newheight,'newheightcm')">,因为您的代码中没有使用该名称定义变量,请查看 epascarello 的答案

您可以将您的代码检查为

<script>
function inchestocm(IDin, IDcm) { 
    IDin = document.getElementById(IDin);
    var inches = IDin.value;
    var centimeters = inches*2.54;  
    document.getElementById(IDcm).value = centimeters;  
}
</script>
<input type="text" id="newheight" onchange="inchestocm('newheight','newheightcm')">
<input type="text" id="newheightcm">
于 2013-10-14T18:35:06.053 回答