在非常简单的javascript函数中嵌入变量

时间:2013-11-09 09:14:49

标签: javascript html

嗨,由于某种原因,我无法使用此功能。

function go(type)
{
    location=document.category.example.options[document.category.example.selectedIndex].value
}

我想要做的就是嵌入类型变量,每当我尝试执行类似

之类的操作时,go函数都会变为未定义
location=document.'+type+'.example.options[document.'+type+'.example.selectedIndex].value

我做错了什么?

3 个答案:

答案 0 :(得分:1)

您可以使用document[type].example

答案 1 :(得分:1)

而不是document.'+type+'.example.options[document.'+type+'.example.selectedIndex].value你应该写:

document[type].example.options[document[type].example.selectedIndex].value

答案 2 :(得分:1)

在执行此类操作之前,您需要了解有关JavaScript语法的更多信息。

以下是您问题的解决方案:

function go(type)
{
    location=document[type].example.options[document[type].example.selectedIndex].value;
}

go('category');

它利用了这两个是等价的事实:

a.b === a['b']

但显然在第二部分中,b可以动态替换,因为它是一个字符串。