为什么JS变量未定义?

时间:2013-10-04 18:20:57

标签: javascript

这很奇怪 - 我一定错过了什么!我有这个简单的js事情,就像这样;

<select onchange='my_function(this.options[this.selectedIndex].value),\"my_text\"'>

和JS简单;

function my_function(selected, text) {
    var link="file.php?var1="+selected+"&var2="+text;
    document.write(link);
}

但我一直得到link = file.php?var1 = selected&amp; var2 = undefined

我有一个几乎相同的功能,工作正常!

3 个答案:

答案 0 :(得分:2)

你的选择html应该是这样的:

<select onchange="my_function(this.options[this.selectedIndex].value,'my_text')">

您过早关闭了函数调用。另外,请注意我已将外部引号切换为double,内部引号为单引号。你不需要逃避内部引用,而且更常见的是,引用属性是双引号而不是单引号。

答案 1 :(得分:1)

您没有将第二个值传递给函数。它在函数调用之外(并且仅作为无效标记)。尝试:

<select onchange="my_function(this.options[this.selectedIndex].value, 'my_text')">

我在这里改变了两件事:

  1. my_text值移至函数调用中。
  2. 更改了引号。 HTML需要双引号,JavaScript可以使用单引号或双引号。因此,在这种情况下,使用双引号来表示HTML标记和内联JavaScript中的单引号更为明确。

答案 2 :(得分:0)

取代:

<select onchange='my_function(this.options[this.selectedIndex].value),\"my_text\"'>

用这个:

<select onchange='my_function(this.options[this.selectedIndex].value),"my_text"'>

因为\是一个转义字符,它会导致您将文本作为my_text而不是"my_text"传递,并且在第一个字符中不是正确的字符串。

我认为您尝试在字符串上添加"引号,但查询字符串默认为字符串,如果仍然需要,则无需添加引号,然后尝试:

<select onchange='my_function(this.options[this.selectedIndex].value),"\"my_text\""'>
相关问题