我有一张包含以下select
<div class="styled-select styled-input">
<select name="upcp-sort-by" id="upcp-sort-by" onchange="UPCP_Sort_By();">
<option value="price_asc">Price (Ascending)</option>
<option value="price_desc">Price (Descending)</option>
</select>
</div>
我想用jquery / JavaScript替换select的文本和另一个文本。我试过这个question:
$(".styled-select").text(function () {
return $(this).text().replace("Price (Ascending)", "Vol (Ascending)");
});
但它破坏了选择选项..
$(".styled-select").text(function() {
return $(this).text().replace("Price (Ascending)", "Vol (Ascending)");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="styled-select styled-input">
<select name="upcp-sort-by" id="upcp-sort-by" onchange="UPCP_Sort_By();">
<option value="price_asc">Price (Ascending)</option>
<option value="price_desc">Price (Descending)</option>
</select>
</div>
&#13;
如何才能正确替换选择文本?
答案 0 :(得分:1)
有两个错误
您需要更改option
的文字,而不是select
元素。
您需要将替换后的值设置回option
元素。
即
$(".styled-select option").each(function() {
$(this).text( $(this).text().replace("Price (Ascending)", "Vol (Ascending)") );
});
<强>演示强>
$(".styled-select option").each(function() {
$(this).text( $(this).text().replace("Price (Ascending)", "Vol (Ascending)") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="styled-select styled-input">
<select name="upcp-sort-by" id="upcp-sort-by" onchange="UPCP_Sort_By();">
<option value=""></option><option value="price_asc">Price (Ascending)</option>
<option value="price_desc">Price (Descending)</option>
</select>
</div>
或使用contains
缩小option
以进行迭代
$(".styled-select option:contains(Price (Ascending))").each(function() {
$(this).text( $(this).text().replace("Price (Ascending)", "Vol (Ascending)") );
});
答案 1 :(得分:1)
您可以编写一个干净的代码,首先选择包含您要替换的文本的option
元素,然后替换text
的{{1}}内容:
option
//get the desired option
var option = $(".styled-select option:contains(Price (Ascending))");
//replace the text
var replacedText = option.text().replace("Price (Ascending)", "Vol (Ascending)");
//set the replaced text
option.text(replacedText);