我有一个下拉菜单,其中我试图获取锚标记中的文本,以便在单击单个按钮时动态更改span标记内的文本。目前我能够做到,但正如您从下面的代码中看到的那样,脚本很容易变得太长。因此,我相信有一种更简单的方法可以使用类,尽管我正在努力成功地做到这一点。
$(".menu__item").click(function() {
var btnId = $(this).attr('data-btnId');
$(".selecBox").text('Example');
$('.menu').removeClass('-is--open');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="position: relative;">
<a class="dropdown -spacing--dense" role="button" style="text-decoration: none;">
<span class="selecBox">Arizona</span><i class="fa fa-chevron-down"></i></a>
<div class="menu -theme--light -position--below -align--left">
<a class="menu__item" role="button" aria-pressed="true" data-btnId="btn1">Arizona</a>
<a class="menu__item" role="button" aria-pressed="true" data-btnId="btn2">California</a>
<a class="menu__item" role="button" aria-pressed="true" data-btnId="btn3">Colorado</a>
<a class="menu__item" role="button" aria-pressed="true" data-btnId="btn4">Delaware</a>
</div>
</div>
答案 0 :(得分:2)
使用$(this).text()
$(".menu__item").click(function() {
var btnId = $(this).attr('data-btnId');
$(".selecBox").text($(this).text());
$('.menu').removeClass('-is--open');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="position: relative;">
<a class="dropdown -spacing--dense" role="button" style="text-decoration: none;">
<span class="selecBox">Arizona</span><i class="fa fa-chevron-down"></i></a>
<div class="menu -theme--light -position--below -align--left">
<a class="menu__item" role="button" aria-pressed="true" data-btnId="btn1">Arizona</a>
<a class="menu__item" role="button" aria-pressed="true" data-btnId="btn2">California</a>
<a class="menu__item" role="button" aria-pressed="true" data-btnId="btn3">Colorado</a>
<a class="menu__item" role="button" aria-pressed="true" data-btnId="btn4">Delaware</a>
</div>
</div>
&#13;