2 回答
![?](http://img1.sycdn.imooc.com/5458626a0001503602200220-100-100.jpg)
TA贡献1829条经验 获得超6个赞
试试这个 usingclosest()方法来找到正确的元素。
$(".dropdown-menu a ").click(function() {
$image = $(this).find('img').attr("src")
$(this).closest('.input-group-btn').find('button img').attr("src", $image);
$(this).closest('.input-group-btn').find('button span').text($(this).text());
});
img {
width: 24px;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown">
<img src="https://i.postimg.cc/44bmkyGL/sdgs-1.jpg"> <span>One</span>
</button>
<div class="dropdown-menu">
<a class="dropdown-item sectionScroll" href="#one"><img src="https://i.postimg.cc/44bmkyGL/sdgs-1.jpg"> One</a>
<a class="dropdown-item sectionScroll" href="#two"> <img src="https://i.postimg.cc/4NWyy0mp/sdgs-2.jpg"> Two</a>
<a class="dropdown-item sectionScroll" href="#three"> <img src="https://i.postimg.cc/dVD1y9yp/sdgs-3.jpg"> Three</a>
<a class="dropdown-item sectionScroll" href="#three"> <img src="https://i.postimg.cc/pdFL0XkB/sdgs-4.jpg"> Four</a>
<a class="dropdown-item sectionScroll" href="#three"> <img src="https://i.postimg.cc/85gPxQ0g/sdgs-5.jpg"> Five</a>
</div>
</div>
</div>
![?](http://img1.sycdn.imooc.com/5458683f00017bab02200220-100-100.jpg)
TA贡献2019条经验 获得超9个赞
你可以试试这个:
$(".dropdown-menu a ").click(function(){
$image=$(this).children('img').attr("src")
$(this).parents(".input-group-btn").find('.btn').children('img').attr("src",$image);
$(this).parents(".input-group-btn").find('.btn').text($(this).text()); });
添加回答
举报