我想通过单击另一个按钮来更改元素的文本。因此,如果我单击带有文本的按钮,所需元素将获得相同的文本。
这是为 Halo 5 Guardians - PC 版制作的粉丝游戏菜单。 它将成为玩家利用自己优势的工具。
<div class="left_menu" id=left_menu>
<button id="option1" class="left_menu-option">option 1</button>
<button id="option2" class="left_menu-option">option 2</button>
<button id="option3" class="left_menu-option">option 3</button>
</div>
<div>
<button class="left_menu-open" id="left_menu_open">
<span class="button-text">text goes here</span>
</button>
</div>
我试过使用下拉菜单和选择菜单,但主要要求是需要更改文本的按钮可以与选项位于单独的 div 中。
最佳答案
您应该使用 .text()
函数,这样您就可以在按钮中设置 span
的文本。它还可以让您从单击的按钮中获取文本。
N.B. you're naming convention was a little odd so I've changed
.left_menu-option
to.left_menu_option
so that it is consistent with the convention you've used for the button (#left_menu_open
).
演示
// Add click event to all buttons with the class .left_menu-option
$(".left_menu_option").click( function() {
// Set the text of the button
$("#left_menu_open .button-text").text($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="left_menu" id=left_menu>
<button id="option1" class="left_menu_option">option 1</button>
<button id="option2" class="left_menu_option">option 2</button>
<button id="option3" class="left_menu_option">option 3</button>
</div>
<div>
<button class="left_menu-open" id="left_menu_open">
<span class="button-text">text goes here</span>
</button>
</div>
关于javascript - 从选项更改元素的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56567276/