简体   繁体   English

使用JQuery选择下拉值时,类未更改

[英]Class not changing when dropdown value is selected with JQuery

What I am trying to accomplish is that when a user selects a value from a dropdown box the corresponding row will change to a different color depending on the option selected. 我要完成的工作是,当用户从下拉框中选择一个值时,相应的行将根据选择的选项更改为其他颜色。

So far I have the rows changing colors just fine but if the user changes their mind and wants to select a new option the row sometimes doesnt change colors. 到目前为止,我让行更改颜色就很好了,但是如果用户改变主意并想要选择新选项,则该行有时不会更改颜色。 The change is sporadic and sometimes the color will change again sometimes it will not. 变化是零星的,有时颜色会再次改变,有时则不会。

Simplified HTML table: 简化的HTML表:

<table class="table" id="myTable">
    <tbody>
    <tr>
      <td>1.</td>
      <td>
        <select name="queue" class="queue-drop">
          <option></option>
          <option class="move">Move</option>
          <option class="add">Add</option>
          <option class="change">Change</option>
          <option class="cancel">Cancel</option>
          <option class="swap">Swap</option>
        </select>
      </td>
    </tr>
    <tr>
    <td>2.</td>
      <td>
        <select name="queue" class="queue-drop">
          <option></option>
          <option class="move">Move</option>
          <option class="add">Add</option>
          <option class="change">Change</option>
          <option class="cancel">Cancel</option>
          <option class="swap">Swap</option>
        </select>
      </td>
    </tr>
    </tbody>
  </table>

JQuery: jQuery的:

$(document).ready(function(){
$('.queue-drop').change(function(){
  var selectedVal = $(this).find("option:selected").text();
  if (selectedVal == 'Move') {
    $(this).closest('tr').addClass("move-row")
  }
  else if (selectedVal == "Add") {
    $(this).closest('tr').addClass("add-row")
  }
  else if (selectedVal == "Cancel") {
    $(this).closest('tr').addClass("cancel-row")
  }
  else if (selectedVal == "Change") {
    $(this).closest('tr').addClass('change-row')
  }
  else if (selectedVal == "Swap") {
    $(this).closest('tr').addClass('swap-row')
  }

});

}); });

JS Fiddle: http://jsfiddle.net/exx2q/ JS小提琴: http//jsfiddle.net/exx2q/

I am somewhat new to JS and JQuery any help would be appreciated. 我是JS和JQuery的新手,将不胜感激。

You can use .removeClass() , to clear class and then apply the new one 您可以使用.removeClass()清除类,然后应用新的类

 $(this).closest('tr').removeClass().addClass("move-row")

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM