如何使用 javascript 将文本附加到 select 选项文本的末尾?
How do I append text to the end of a select option's text using javascript?
您好,我有一个动态拉出的 select 选项菜单,我想在选项文本的末尾为某些口味添加一条消息,说“新”或“员工选择” " 例如。
在这种情况下,我想将“Staff Pick”添加到 Banana & Kiwi 的末尾。我该怎么做?到目前为止,我已经能够针对这两种口味,但不确定如何将副本添加到每种口味的末尾。如有任何帮助,我们将不胜感激
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>
您已经完成了困难的工作 - 只需更改元素的 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>
您好,我有一个动态拉出的 select 选项菜单,我想在选项文本的末尾为某些口味添加一条消息,说“新”或“员工选择” " 例如。
在这种情况下,我想将“Staff Pick”添加到 Banana & Kiwi 的末尾。我该怎么做?到目前为止,我已经能够针对这两种口味,但不确定如何将副本添加到每种口味的末尾。如有任何帮助,我们将不胜感激
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>
您已经完成了困难的工作 - 只需更改元素的 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>