gpt4 book ai didi

javascript - 从下拉菜单中选择元素

转载 作者:行者123 更新时间:2023-11-28 10:09:33 25 4
gpt4 key购买 nike

我已经构建了一个 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>

最佳答案

你必须这样做:

$(".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 的 anchor 标记获取它的文本 val() 仅适用于表单和 ul 的输入元素,li 和 a 不是输入元素,您必须使用 text() 获取它的值并将其显示为选中的将事件类添加到单击的类并从其他类中删除

FIDDLE DEMO

关于javascript - 从下拉菜单中选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com