简体   繁体   English

jQuery on change在select上触发两次

[英]jQuery on change trigger twice on select

I have problem with jQuery change connected with select tag. 我有与jQuery更改连接select标签的问题。 It fire twice, second time returning empty array. 它发射两次,第二次返回空阵列。 jQuery or JS is NOT included twice, already checked. jQuery或JS不包括两次,已经检查过。

I would be very grateful for any help in this area :) 我非常感谢这方面的任何帮助:)

JS JS

  $(".select-car").on("change", function(){
    var cars = [];
    var carType = $(this).val();
    $.getJSON("js/cars.json", function(data) {
      $.each(data, function(i, item) {
        // console.log(item);
        if(item.type === carType) {
          cars.push(item);
        }
      });
    });
    console.log(cars);
  });

HTML HTML

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="css/main.css">
  <title>Wyporzyczalnia samochodów</title>
</head>
<body>

  <main class="container main-container">
    <div class="row select-car">
      <div class="col-md-12 header">
        <h2 class="page-header">Wybierz typ samochodu</h2>

        <form action="">
          <select name="cartype" class="form-control select-car">
            <option value="" selected="true" disabled>---</option>
            <option value="camper">Camper</option>
            <option value="limuzyna">Limuzyna</option>
            <option value="osobowy">Osobowy</option>
          </select>
        </form>
      </div>
    </div> <!-- Select car -->

    <div class="row avaible-cars">


    </div>


  </main>

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>

You have two classes .select-car 你有两个班.select-car

<div class="row select-car">

and in 并在

<select name="cartype" class="form-control select-car">

Which is causing this to be called twice. 这导致两次被调用。 And hence binded the change event twice. 因此将变更事件绑定两次。

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

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