什么时候需要对document.getElementByID进行引号? [英] When do I need quotes for document.getElementByID?

查看:121
本文介绍了什么时候需要对document.getElementByID进行引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple script which converts a text input of inches into another text input of centimeters. However, when I pass it to my function, I noticed that I have to use quotes for the argument passed to document.getElementByID. I tried newheightcm without quotes and it failed. Is there a way to avoid this to maintain consistency for both arguments, i.e. both have quotes or both have no quotes?

<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">

推荐答案

由于没有引号,因此您正在寻找在全局范围内定义的变量newheight.一些浏览器做了一件坏事,并说如果我没有具有该ID的变量,我会寻找具有该ID的DOM元素.

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.

因此,您要传入的是具有该ID而不是字符串的DOM元素.这就是IDin.value起作用的原因.

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.

这篇关于什么时候需要对document.getElementByID进行引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆