如果您不想更改html,
您可以使用
nodeType===3
筛选出中的所有文本内容
$(.menu-btn).contents()
,然后将其替换为所需的值。
$("body").on("click", ".btn-opt", function(event) {
var $el = $(this);
var id = $el.attr("id");
$(this)
.parent()
.parent()
.find("span.selected")
.removeClass("active");
$el.find("span.selected").addClass("active");
$(".menu-btn > i:first-child")
.removeClass()
.addClass("fa fa-fw fa-" + id);
// find out all text content (nodeType===3), then replace with yours
//.each is not required, you can change to [0].textContent = 'yourConent' if make sure at least exists one text content.
$(".menu-btn").contents().filter(function() {
return this.nodeType == 3
}).each(function(){
this.textContent = $el.find('label').text();
});
$(".menu-btn")
.removeClass()
.addClass("menu-btn btn btn-primary fg-" + id);
});
<link href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex">
<div class="menu-btn btn fg-create"><i class="fa fa-plus fa-fw"></i><i class="arrow fa fa-fw"></i>Menu</div>
<div class="menu">
<div class="btn-opt btn fg-shopping-bag" id="shopping-bag">
<label for="shopbtn"><input id="shopbtn" name="toggler" type="radio"><i class="fa fa-fw fa-shopping-bag"></i> Bag</label>
</div>
<div class="btn-opt btn fg-rocket" id="rocket">
<label for="rocketbtn"><input id="rocketbtn" name="toggler" type="radio"><i class="fa fa-fw fa-rocket"></i> Rocket</label>
</div>
</div>
</div>