2017-02-23 24 views
1

我正在尝试学习onChange函数。我抓住了这段代码并在我的网站上实现了它,并且它正在工作,它实际上显示了用户选择的值,但是当我尝试控制台在Chrome中记录变量时,它会显示: Uncaught ReferenceError: x is not defined。这是为什么?为什么变量在我选择了一辆汽车之后还没有定义。还有一个问题。这是JavaScript还是JQuery?将所选选项存储为javascript变量

<!DOCTYPE html> 
<html> 
<body> 

<p>Select a new car from the list.</p> 

<select id="mySelect" onchange="myFunction()"> 
    <option value="Audi">Audi 
    <option value="BMW">BMW 
    <option value="Mercedes">Mercedes 
    <option value="Volvo">Volvo 
</select> 

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p> 

<p id="demo"></p> 

<script> 
function myFunction() { 
    var x = document.getElementById("mySelect").value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
} 
</script> 

</body> 
</html> 
+0

不是您的问题的一部分,您的选择有没有关闭标签:'' –

回答

2

这是您的帖子中的JavaScript。

如果你这样做:

function myFunction() { 
    var x = document.getElementById("mySelect").value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
    console.log("x:",x); 
} 

x是函数的范围,从而可用。

在全局范围内定义像那样的变量通常是一种糟糕的做法。

var x = {}; 
function myFunction() { 
    x = document.getElementById("mySelect").value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
} 
myfunction();// call it 
console.log("x:",x); 

这个详细的版本:(基本上在对象相同,但明确window)请注意我说怎么去选择的值。

window.x = {}; 

function myFunction() { 
    window.console.log("in here"); 
    var selectElem = document.getElementById("mySelect"); 
    var optsCount = selectElem.options.length; 
    var index = selectElem.selectedIndex; 
    window.console.log("opts", optsCount, index); 
    // return the value of the selected option 
    window.console.log(selectElem.options[selectElem.selectedIndex].value) 
    window.x = selectElem.options[selectElem.selectedIndex].value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
} 
window.myFunction(); // call it 
window.console.log("x:", window.x); 

下面是最后一个例子的小提琴:https://jsfiddle.net/MarkSchultheiss/bqwd784p/

没有这里的jQuery JavaScript的公正。

+0

非常感谢你描述的答案。我学到了很多,并使其工作:-) –

2

你的变量声明,并在功能范围分配的代码。如果你想它提供的功能范围之外,你需要声明它的功能之外

<script> 
var x; 
function myFunction() { 
    x = document.getElementById("mySelect").value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
} 
</script> 

这将是不确定的,直到你的功能被触发。这是使用DOM API的普通香草JS。

+0

我会尽力的。谢谢。 –

+0

@KakiSami或者,您可以使用'window.x = document.getElementById(“mySelect”).value'在函数内全局地分配它。 – Bright

+0

非常感谢您的回答。我最终宣布它在飞行中,然后它成为全球。 “format = document.getElementById(”format“)。value” –