将所选选项存储为javascript变量

时间:2017-02-23 19:56:24

标签: javascript html

我正在尝试学习onChange功能。我抓住了这个代码并在我的网站上实现了它并且它正在工作,它实际上显示了用户选择的值,但是当我尝试在chrome中控制日志变量时它说: Uncaught ReferenceError: x is not defined。这是为什么?为什么即使在我选择了汽车之后变量也没有定义。还有一个问题。这是javascript还是Jquery?

代码

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

2 个答案:

答案 0 :(得分:2)

您的变量在函数范围内声明并赋值。如果您希望它在函数范围之外可用,则需要在函数

之外声明它
 $draw->setTextAlignment(\Imagick::ALIGN_CENTER);

在触发您的功能之前,它将是未定义的。这是使用DOM API的普通的JS。

答案 1 :(得分:2)

这是您帖子中的JavaScript。

如果你这样做:

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); )注意我添加了如何获取所选值。

#create function with the given name
# \return the function
def makeFunc(tp):
    methname = "__{:s}__".format(tp)
    print("defining", methname)
    def func(self, other):
        x = getattr(super(Foo, self), methname)(other)
        print("I calculated x={:.3f}!".format(x))
        return x
    func.__name__ = methname
    return func


for tp in ("add", "sub", "mul", "truediv", "floordiv", "mod", "divmod", "pow"):
    func=makeFunc(tp)
    setattr(Foo, func.__name__, func)

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

这里没有jQuery只是JavaScript。