1
我想将我的“主”按钮上的文本替换为在下拉菜单中单击的列表“项目”文本。我使用的jQuery代码不起作用。我尝试了其他的选择,但他们也没有工作。有什么办法可以解决这个问题吗?对不起,烦扰如何使用jQuery替换按钮的文本与列表项文本?
我想将我的“主”按钮上的文本替换为在下拉菜单中单击的列表“项目”文本。我使用的jQuery代码不起作用。我尝试了其他的选择,但他们也没有工作。有什么办法可以解决这个问题吗?对不起,烦扰如何使用jQuery替换按钮的文本与列表项文本?
您有几个选择器错误。
更改此:
$(function(){
$(".dropdown-menu a").click(function(){
$(".dropbtn:first-child").text($(this).text());
$(".dropbtn:first-child").val($(this).text());
});
});
要这样:
$(function() {
$(".dropdown-content a").click(function() {
$('#mainspan').text($(this).text());
$(".dropdown-content").toggle();
});
});
代码段:
/* Main menu drops on click */
$(document).ready(function() {
$(".dropbtn").click(function() {
$(this).toggleClass('active');
$(".dropdown-content").toggle();
});
});
/* Code to replace button's text */
$(function() {
$(".dropdown-content a").click(function() {
$('#mainspan').text($(this).text());
$(".dropdown-content").toggle();
});
});
.dropdown-main {
position: relative;
display: inline-block;
}
.dropbtn {
width: 115px;
height: 28px;
border: solid 1px #cebbb1;
background-color: white;
color: #897f63;
margin-left: -5px;
position: relative;
cursor: pointer;
}
.dropbtn.active {
border: solid 1px #0093dc;
color: #0093dc;
}
#mainspan {
font-weight: bold;
position: absolute;
padding-left: 7px;
padding-top: 4px;
}
.dropdown-content {
display: none;
position: absolute;
background-color: white;
min-width: 160px;
z-index: 1;
border: solid 1px #cebbb1;
width: 170px;
margin-left: -5px;
}
.dropdown-content a {
padding: 1px 14px;
display: block;
color: #897f63;
text-decoration: none;
}
.dropdown-content a:hover {
background-color: #f1f1f1;
text-decoration: none;
color: #897f63;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="TEXTREPLACE.css">
</head>
<body>
<div class="dropdown-main">
<div class="dropbtn">
<span id="mainspan">Main</span>
</div>
<div class="dropdown-content">
<a href="#">Item 1</a>
<a href="#">Item 2</a>
<a href="#">Item 3</a>
</div>
</div>
<script type='text/javascript' src="TEXTREPLACE.js"></script>
</body>
</html>
唷,这太混乱了!非常感谢您的帮助,这个解决方案很容易解决我的问题! – confused5000