选择optgroup上的click事件无法正常工作

时间:2018-09-18 11:57:28

标签: optgroup

我有以下带有optgroup的选择菜单示例:

<!DOCTYPE html>
<html>
<head>
<title>Try jQuery Online</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  var opt = {
    friendchat:[
        {name:"somefriend1-1", number:"12"},
        {name:"somefriend2 11", number:"23"}
    ],
    otherchat:[
        {name:"someother1", number:"34"},
        {name:"someother2", number:"45"}
    ],
    friendrequest:[
        {name:"somerequest1", number:"56"},
        {name:"somerequest2", number:"67"}
    ],
    sentrequest:[
        {name:"somesent1", number:"78"},
        {name:"somesent2", number:"89"}
    ]
};

$(function(){
    var $select = $('#mySelect');
    $.each(opt, function(key, value){
        var group = $('<optgroup label="' + key + '" />');
        $.each(value, function(){
            $('<option value=' + this.name + '/>').html(this.name).appendTo(group);
        });
        group.appendTo($select);
    });
    $("#mySelect").change(function(){
        $("#selectedValue").html($(this)[0].value);     
    });
});
});

</script>
</head>
<body>
<select id="mySelect" size="9">
</select>
<h3>Selected Value from optgroup </h3>
<h3 id="selectedValue"></h3>
</body>
</html>

如果我们从下拉菜单中选择第二个选项,即“ somefriend2 11”,其中包含空格,则输出将以“ somefriend2 11”而不是“ somefriend2 11”出现。

我无法找出问题所在。 有人可以检查一下代码有什么问题吗?

0 个答案:

没有答案