JQuery:包含在if语句中的计数器不起作用?

时间:2016-05-11 03:00:24

标签: javascript jquery

所以我有两个这样的选择菜单,我希望每次在每个选择中选择一个右选择时,计数器加1。但它保持在1 ..我该如何解决这个问题?

HTML:

<div class="row"><!--first row-->

        <div class="col-sm-3 col-xs-12 unit" >
            <img src="img/shiny-apple.png" id="apple">
            <p class="selectby">Fruit</p>
            <select>
              <option value="default"></option>
              <option value="apple">apple</option>
              <option value="banana">banana</option>
              <option value="grapes">grapes</option>
              <option value="carrot">carrot</option>
            </select>
        </div><!-- end of col-->

        <div class="col-sm-3 col-xs-12 unit" >
            <img src="img/carrot.png" id="carrot">
            <p class="selectby">Fruit</p>
            <select>
              <option value="default"></option>
              <option value="apple">apple</option>
              <option value="banana">banana</option>
              <option value="grapes">grapes</option>
              <option value="carrot">carrot</option>
            </select>
        </div><!-- end of col-->

JS:

$("select").change(function() {

$selectedItem = $(this).val();
$imgId = $(this).siblings().attr('id');
var counter = 0;

// if the image ID string includes the selected option string
if ( $imgId.includes($selectedItem) ) {
    $(this).parent().css("background-color", "lightgreen");
    $(this).prop('disabled', true);

    counter++;
    console.log(counter);
}

});

1 个答案:

答案 0 :(得分:2)

&#13;
&#13;
var counter = 0;//put counter outside of change so it wont be initialize to 0 every change event
$("select").change(function() {

  $selectedItem = $(this).val();
  $imgId = $(this).siblings().attr('id');


  // if the image ID string includes the selected option string
  if ($imgId.includes($selectedItem)) {
    $(this).parent().css("background-color", "lightgreen");
    $(this).prop('disabled', true);

    counter++;
    console.log(counter);
  }
alert(counter)
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <!--first row-->

  <div class="col-sm-3 col-xs-12 unit">
    <img src="img/shiny-apple.png" id="apple">
    <p class="selectby">Fruit</p>
    <select>
      <option value="default"></option>
      <option value="apple">apple</option>
      <option value="banana">banana</option>
      <option value="grapes">grapes</option>
      <option value="carrot">carrot</option>
    </select>
  </div>
  <!-- end of col-->

  <div class="col-sm-3 col-xs-12 unit">
    <img src="img/carrot.png" id="carrot">
    <p class="selectby">Fruit</p>
    <select>
      <option value="default"></option>
      <option value="apple">apple</option>
      <option value="banana">banana</option>
      <option value="grapes">grapes</option>
      <option value="carrot">carrot</option>
    </select>
  </div>
  <!-- end of col-->
&#13;
&#13;
&#13;

将计数器放在更改事件之外。因为每个更改事件都会再次初始化为0