jQuery:基于<option> Selected </option>进行导航

时间:2012-02-02 19:12:09

标签: jquery

新手问题:

在jQuery中,如何在选择时让浏览器导航到所选的饮料?

<select name="selDrink" id="selDrink">
    <option value="http://coke.com">Coke</option>
    <option value="http://pepsi.com">Pepsi</option>
</select>

4 个答案:

答案 0 :(得分:1)

//select the element and bind a `change` event handler to it
$('#selDrink').on('change', function () {

    //redirect the user to the value of the select element
    window.location = this.value;
});

您可能希望在顶部显示空白<option>,以便可以选择具有实际<option>的所有value

HTML -

<select name="selDrink" id="selDrink">
    <option value="">Choose One</option>
    <option value="http://coke.com">Coke</option>
    <option value="http://pepsi.com">Pepsi</option>
</select>

JS -

$('#selDrink').on('change', function () {

    //check if the selected value of this element is blank, if not then redirect to the value
    if (this.value != '') {
        window.location = this.value;
    }
});

请注意,.on()是jQuery 1.7中的新功能,在这种情况下使用的是.bind()

以下是演示:http://jsfiddle.net/Duanx/

window.location的文档:https://developer.mozilla.org/en/DOM/window.location

答案 1 :(得分:1)

$("#selDrink").change(function () {
    window.location.href = $(this).val();
});

答案 2 :(得分:1)

<select name="selDrink" id="selDrink">
    <option>Select a Drink</option>
    <option value="http://coke.com">Coke</option>
    <option value="http://pepsi.com">Pepsi</option>
</select>

<script>

   $( '#selDrink' ).change( function navigate() {

        window.location.href = $( this ).val();
    });

</script>

答案 3 :(得分:1)

$(function(){
    $('#selDrink').change(function(){
        window.location.href = $(this).val();
    });
});