【问题标题】:Select option and change class ul li选择选项并更改类 ul li
【发布时间】:2018-06-22 08:50:19
【问题描述】:

我的代码

 <select id="jform_parent_id" name="jform[parent_id]">
        <option value="1">Public</option>
        <option value="8">- Admingruppe</option>
        <option value="9">- Guest</option>
        <option value="2">- Projektgruppe</option>
    </select>
    <ul class="chzn-results">
        <li class="active-result result-selected" data-option-array-index="0">Public</li>
        <li class="active-result" data-option-array-index="1">- Admingruppe</li>
        <li class="active-result" data-option-array-index="2">- Guest</li>
        <li class="active-result" data-option-array-index="3">- Projektgruppe</li>
    </ul>

我想: 选择选项值=2 将类 result-selected 添加到 ul li data-option-array-index="3" 删除其他地方选择的类结果

感谢您的帮助

【问题讨论】:

标签: jquery


【解决方案1】:

这比您想象的要容易。您需要做的就是:

$(function () {
  // On change of the select...
  $("#jform_parent_id").change(function () {
    // Get the current selected index.
    var sIndex = this.selectedIndex;
    // Now find the <li> with correct data-option-array-index and add the class.
    $(".result-selected").removeClass("result-selected");
    $('li[data-option-array-index="' + (sIndex) + '"]').addClass("result-selected");
  });
});

这里有完整的片段:

$(function () {
  // On change of the select...
  $("#jform_parent_id").change(function () {
    // Get the current selected index.
    var sIndex = this.selectedIndex;
    // Now find the <li> with correct data-option-array-index and add the class.
    $(".result-selected").removeClass("result-selected");
    $('li[data-option-array-index="' + (sIndex) + '"]').addClass("result-selected");
  }).val("2").trigger("change");
});
.result-selected {background: #99f;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="jform_parent_id" name="jform[parent_id]">
  <option value="1">Public</option>
  <option value="8">- Admingruppe</option>
  <option value="9">- Guest</option>
  <option value="2">- Projektgruppe</option>
</select>
<ul class="chzn-results">
  <li class="active-result result-selected" data-option-array-index="0">Public</li>
  <li class="active-result" data-option-array-index="1">- Admingruppe</li>
  <li class="active-result" data-option-array-index="2">- Guest</li>
  <li class="active-result" data-option-array-index="3">- Projektgruppe</li>
</ul>

更新:在页面加载时使用了预选值。

【讨论】:

  • 非常感谢 Praveen Kumar!但我需要在页面加载时预先选择值 2,我希望它是我的默认选择值
  • @ErickBoileau 使用这种方式&lt;option value="2" selected&gt;- Projektgruppe&lt;/option&gt;。我现在会更新我的答案。
  • @ErickBoileau 检查我的答案。
  • 谢谢,但那是我的问题,如何将选定的值添加到值 2?
  • 我不知道为什么它在这里工作而不是在我的网站上我无法在你的代码中找到你如何选择选项值 = 2 无论如何谢谢!
猜你喜欢
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 2021-07-03
  • 2013-05-26
相关资源
最近更新 更多