使用Javascript根据下拉菜单中选择的选项更改URL

使用Javascript根据下拉菜单中选择的选项更改URL

本文介绍了使用Javascript根据下拉菜单中选择的选项更改URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法使它正常工作。有什么想法吗?

I cannot seem to get this to work. Any thoughts?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select Video Test</title>
<script type="text/javascript">
    function selectVideo(){
        var urlString = "http://www.mycookingsite.com/";
        var selectedVideo = this.options[this.selectedIndex];
        if (selectedVideo.value != "nothing"){
            window.location = urlString + selectedVideo.value;
        }
    }
</script>
</head>

<body>

<form>
    <select onchange="selectVideo()">
    <option value="nothing">Select video from this list</option>
    <option value="how-to-grill-burgers">How to Grill Burgers</option>
       <option value="how-to-hard-boil-eggs">How to Make Hard-Boiled Eggs</option>
    </select>
</form>
</body>
</html>


推荐答案

您只能使用 this (当您使用事件代码时)。当您使用该函数时, this 引用窗口对象。将引用作为参数发送给函数:

You can only use this when you are in the event code. When you are in the function, this referrs to the window object. Send the reference as a parameter to the function:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select Video Test</title>
<script type="text/javascript">
    function selectVideo(obj){
        var urlString = "http://www.mycookingsite.com/";
        var selectedVideo = obj.options[obj.selectedIndex];
        if (selectedVideo.value != "nothing"){
                window.location = urlString + selectedVideo.value;
        }
    }
</script>
</head>

<body>

<form>
    <select onchange="selectVideo(this)">
    <option value="nothing">Select video from this list</option>
    <option value="how-to-grill-burgers">How to Grill Burgers</option>
       <option value="how-to-hard-boil-eggs">How to Make Hard-Boiled Eggs</option>
    </select>
</form>
</body>
</html>

这篇关于使用Javascript根据下拉菜单中选择的选项更改URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 14:18