从下拉菜单中选择项目

时间:2014-06-26 18:46:56

标签: javascript jquery html css drop-down-menu

我已经构建了一个css下拉菜单,当我从中选择并选择它时,我希望它确保下拉列表中的所选选项,但它显示了同样的事情,并没有改变...我是使用jQuery,我认为混淆来自ul和li以及我的选择器必须是什么。

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
    <title></title>

    <style>

.dropdown-menu {
    padding: 0;
    margin: 0;
    width: 130px;
    font-family: Arial;
    display: inline-table;
    position: relative;
    border: solid 1px #CCCCCC;
    border-bottom-style: none;
    background-color: #F4F4F4;
}
.dropdown-menu .menu-item {
    display: none;
}
.dropdown-menu .menu-item-link {
    display: table-cell;
    border-bottom: solid 1px #CCCCCC;
    text-decoration: none;
    color: rgba(89,87,87,0.9);
    height: 30px;
    padding: 5px;
    vertical-align: middle;
    cursor: pointer;
}
.dropdown-menu:hover .menu-item {
    border-bottom-style: solid;
}
.dropdown-menu .menu-item-link:hover {
    background-color: #DDDDDD;
}

.dropdown-menu:hover .menu-item {
    display: table-row;
}
.dropdown-menu .menu-item.active {
    display: table-header-group;
}
.dropdown-menu .menu-item.active .menu-item-link:after {
    width: 0; 
    height: 0; 
    content: "";
    position: absolute;
    top: 12px;
    right: 8px;
    border-top: 4px solid rgba(0, 0, 0, 1);     
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;

}



    </style>
</head>
<body>

<script>

$(document).ready(function(){

    $("#account").click(function () {

    alert($('.menu-item').val());

    });


</script>



<ul class = "dropdown-menu">
    <li class = "menu-item">
        <a href = "#" class = "menu-item-link" id="account">account</a>
    </li>
    <li class = "menu-item">
        <a href = "#" class = "menu-item-link" id="gametime">gametime</a>
    </li>
    <li class = "menu-item">
        <a href = "#" class = "menu-item-link" id="RPA">Cereal</a>
    </li>
    <li class = "menu-item">
        <a href = "#" class = "menu-item-link" id="workhard">workhard</a>
    </li>
    <li class = "active menu-item">
        <a href = "#" class = "menu-item-link" id="puppies">puppies</a>
    </li>            
</ul>
</select>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

你必须这样做:

$(".dropdown-menu .menu-item a").click(function () {

    alert($(this).text());
     $(".menu-item").removeClass("active"); // remove active class from li tags
     $(this).closest("li").addClass("active"); // add active class to current clicked one

    });

点击li的锚标签得到它的文本val()仅适用于表单的输入元素,而ul,li和a不是输入元素,你必须使用text()来获取其值和将其显示为已选中添加活动类以单击其中一个并从其他人中删除

FIDDLE DEMO

答案 1 :(得分:0)

检查出来http://jsfiddle.net/DsfU3/I已对字段ID进行了一些更改,看看它是否可以帮助您$(document).ready(function(){ $(".menu-item-link").on('click',function () { $(".menu-item").removeClass("active"); $("#"+$(this).text()).closest("li").addClass("active"); }) });