未选中下拉列表的Jquery值

时间:2015-04-26 15:24:32

标签: jquery

我使用数组填充了一个包含值的下拉列表。但是每当我从下拉列表中获取所选值时,它都没有显示或执行相应的操作。我的代码是:

<script type="text/javascript">
    $("#cat").on('click', function () {
        var data = {
            '1': 'Mock 1',
            '2': 'Mock 2',
            '3': 'Mock 3',
            '4': 'Mock4',
            '5': 'Mock5'
        }

        var s = $('<select id="c" />');

        for(var val in data) {
            $('<option />', {value: val, text: data[val]}).appendTo(s);
        }

        s.appendTo('#f'); // or wherever it should be
    });
    </script>
   <script>

    var m=$( "#c option:selected" ).text();
    alert(m);
    if(m=="Mock 1") {
        var url = "http://www.careerlauncher.com/sis/mba/mock_2_question.pdf";
        $(location).attr('href', url);
    }
    if(m=="Mock 2") {
        var url = "http://www.careerlauncher.com/sis/mba/mock_3_question.pdf";
        $(location).attr('href', url);
    }
    if(m=="Mock 3") {
        var url = "http://www.careerlauncher.com/sis/mba/mock_4_question.pdf";
        $(location).attr('href', url);
    }
    if(m=="Mock4") {
        var url = "http://www.careerlauncher.com/sis/mba/mock_5_question.pdf";
        $(location).attr('href', url);
    }
  </script>

我还尝试将此块放在click事件下,但是当它看到Mock1被选中时,它会重定向到另一个页面,因此用户将无法选择其他选项。请帮我纠正代码。

1 个答案:

答案 0 :(得分:0)

需要包装$(document).ready并移动你的$(“#cat”)。随叫随到......

<script type="text/javascript">
$(document).ready(function(){
    var data = {
        '1': 'Mock 1',
        '2': 'Mock 2',
        '3': 'Mock 3',
        '4': 'Mock4',
        '5': 'Mock5'
    }

    var s = $('<select id="c" />');

    for(var val in data) {
        $('<option />', {value: val, text: data[val]}).appendTo(s);
    }

    s.appendTo('#f'); // or wherever it should be
    $("#cat").on('click', function () {
        var m=$( "#c option:selected" ).text();
        alert(m);
        if(m=="Mock 1") {
            var url = "http://www.careerlauncher.com/sis/mba/mock_2_question.pdf";
            $(location).attr('href', url);
        }
        else if(m=="Mock 2") {
            var url = "http://www.careerlauncher.com/sis/mba/mock_3_question.pdf";
            $(location).attr('href', url);
        }
        else if(m=="Mock 3") {
            var url = "http://www.careerlauncher.com/sis/mba/mock_4_question.pdf";
            $(location).attr('href', url);
        }
        else if(m=="Mock4") {
            var url = "http://www.careerlauncher.com/sis/mba/mock_5_question.pdf";
            $(location).attr('href', url);
        }
    });
});

</script>