简体   繁体   English

如何使用javascript将文本附加到选择选项文本的末尾?

[英]How do I append text to the end of a select option's text using javascript?

Hi i've got a select option menu that is pulled through dynamically, where i want to add a message to certain flavours at the end of the options text to say "New" or "Staff Pick" for example.嗨,我有一个动态拉取的选择选项菜单,我想在选项文本的末尾向某些口味添加一条消息,例如说“新”或“员工选择”。

In this instance I want to add "Staff Pick" to the end of Banana & Kiwi.在这种情况下,我想在 Banana & Kiwi 的末尾添加“员工选择”。 How would i do this?我该怎么做? So far I've been able to target the two flavours but not sure how i would add the copy to the end of each.到目前为止,我已经能够针对这两种口味,但不确定如何将副本添加到每种口味的末尾。 Any help on this would be appreciated对此的任何帮助将不胜感激

 document.querySelectorAll('.form-dropdown').forEach(function(select) { Array.from(select.options).forEach(function(option) { if (option.innerText.includes("Banana") || option.innerText.includes("Kiwi")) { // the below code is set to disabled to show the two flavours have been targeted option.setAttribute("disabled", true); } }); });
 <select class="form-dropdown"> <option disabled="" value="">Choose option</option> <option value="0">Apple</option> <option value="1">Banana</option> <option value="2">Cherry</option> <option value="3">Kiwi</option> <option value="4">Lemon</option> </select>

You've done the hard bit - just change the innerText of the element您已经完成了困难的工作 - 只需更改元素的innerText

 document.querySelectorAll('.form-dropdown').forEach(function(select) { Array.from(select.options).forEach(function(option) { if (option.innerText.includes("Banana") || option.innerText.includes("Kiwi")) { // the below code is set to disabled to show the two flavours have been targeted option.innerText += " (Staff Pick)" } }); });
 <select class="form-dropdown"> <option disabled="" value="">Choose option</option> <option value="0">Apple</option> <option value="1">Banana</option> <option value="2">Cherry</option> <option value="3">Kiwi</option> <option value="4">Lemon</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM