jQuery:OnClick更改选项'selected'属性

时间:2017-09-25 23:08:55

标签: jquery html

这将是我在这里的第二篇文章,如果有人可以用他的魔法知识支持,那将会很棒:)

我想要实现的目标?

更改选项我想从默认设置中删除属性'selected'并添加到我点击的选项。

这是我想要的HTML:

<select class="flex-calc-length">
   <option value="6">1/2 year</option>
   <option value="12" selected>1 year</option>
   <option value="24">2 years</option>
   <option value="36">3 years</option>
   <option value="48">4 years</option>
   <option value="60">5 years</option>
</select>

但总的来说,这是materialize.css选择功能的一部分,它添加了一堆代码,从上面转换为:

<div class="select-wrapper flex-calc-length">
<span class="caret">▼</span>
<input type="text" class="select-dropdown" readonly="true" data-activates="select-options-3062497b-bc40-0e77-91c3-550f09e8e872" value="1 year">
<ul id="select-options-3062497b-bc40-0e77-91c3-550f09e8e872" class="dropdown-content select-dropdown" style="width: 215.2px; position: absolute; top: 0px; left: 0px; display: none; opacity: 1;">
    <li class=""><span>1/2 year</span></li>
    <li class=""><span>1 year</span></li>
    <li class="active selected"><span>2 years</span></li>
    <li class=""><span>3 years</span></li>
    <li class=""><span>4 years</span></li>
    <li class=""><span>5 years</span></li>
</ul>
<select class="flex-calc-length initialized" data-select-id="3062497b-bc40-0e77-91c3-550f09e8e872">
    <option value="6">1/2 year</option>
    <option value="12" selected="">1 year</option>
    <option value="24">2 years</option>
    <option value="36">3 years</option>
    <option value="48">4 years</option>
    <option value="60">5 years</option>
</select>
</div>

1 个答案:

答案 0 :(得分:2)

这是你想要实现的目标吗?

let prevVal = $('.flex-calc-length').val();
function replaceSelection() {
  selectedVal = $('.flex-calc-length').val();
  
  $('.flex-calc-length > option').each(function(i, item) {
    if(item.value === prevVal) {
      $(item).removeAttr("selected");
    }
  })
  
  $('.flex-calc-length > option').each(function(i, item) {
    if(item.value === selectedVal) {
      $(item).attr("selected", "true");
      prevVal = $(item).val();
    }
  })
}
option[selected] {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="flex-calc-length" onchange="replaceSelection()">
   <option value="6">1/2 year</option>
   <option value="12" selected>1 year</option>
   <option value="24">2 years</option>
   <option value="36">3 years</option>
   <option value="48">4 years</option>
   <option value="60">5 years</option>
</select>

如果您需要解释 - 请问。