替换选择表单的文本

时间:2018-03-29 12:40:27

标签: javascript jquery

我有一张包含以下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)"); 
 });

但它破坏了选择选项..

&#13;
&#13;
$(".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;
&#13;
&#13;

如何才能正确替换选择文本?

2 个答案:

答案 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);