【问题标题】:Jquery event of toggle doesn't works after load table加载表后,切换的 Jquery 事件不起作用
【发布时间】:2021-05-02 12:01:48
【问题描述】:

我正在使用 Symfony 进行开发。 在我的页面上,我有一个数据表,每行都有一个切换。提交表单修改该表的一行后,我加载该表。然而,在加载表格(不是整个页面)之后,我的切换的 jQuery 事件不再起作用。 我的页面以 2 个视图分隔。一个用于页面,一个用于页面上的表格。

Javascript:

$(document).ready(
function() {

    // load the table
    $(document).on("click", ".btn-load", function() {

        $('.table').load('/table');

    });


    $("input[type='checkbox']").on('change', function(){
        console.log("Hello I have changed !");
    });

    //toggle 
    $(document).on("change", "input", function() {
        console.log($(this).val());
        let id = $(this).val();
        let isCheck;
        if ($(this).is(":checked") === true) {
            isCheck = 1;
        } else isCheck = 0;

        let url = "/follow";
        let data = {'id': id, 'valeur': isCheck};

        $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: 'html',
            cache: false
        });

    });


});

页面模板:

{% block body %}

  <br>
  <h1><center>Affichage des players</center></h1>

  {% if app.user %}
    <li><a href="/logout">Déconnexion</a></li>
  {% else %}
    <li><a href="/login">Connexion</a></li>
  {% endif %}

  <a
    class="btn-new dt-button buttons-collection buttons-colvis btn btn-white btn-primary btn-bold"
    data-toggle="modal"
    data-target="#dataModal"
    href="#"
  >
    Nouveau Player
  </a>

  <section class="wrapper">
    <div class="row mt">
      <div class="col-md-12">
        <div class="content-panel">

              {% block table %}{% include "manager_temp/table.html.twig" %}{% endblock table %}
        </div>
      </div>
    </div>
  </section>

{% endblock %}

表格模板:

{% block table %}


        <table class="table table-striped table-advance table-hover">
            <h4><i class="fa fa-angle-right"></i> Players</h4>
            <thead>
            <tr>
              <th><i class="fa fa-home"></i> Host</th>
              <th class="hidden-phone"><i class="fa fa-desktop"></i> Dest</th>
              <th><i class=" fa fa-arrows-h"></i> Largeur</th>
              <th><i class=" fa fa-arrows-v"></i> Hauteur</th>
              <th><i class=" fa fa-check-circle"></i> Suivi</th>
              <th><i class=" fa fa-key"></i> ID Xibo</th>
              <th><i class=" fa fa-info-circle"></i> Type</th>
              <th><i class=" fa fa-edit"></i> Actions</th>
              <th></th>
            </tr>
            </thead>

            {% for player in players %}
              <tr>
                  // ------- THIS IS THE TOGGLE ----------
                {% if player.isFollowed == 1 %}
                  <td>
                    <input class="check" id="che" type="checkbox" checked="" value="{{ player.idPlayer }}" data-toggle="switch"/>
                  </td>

                {% else %}
                  <td><input class="check" type="checkbox" value="{{ player.idPlayer }}" data-toggle="switch" /></td>
                {% endif %}

                <td>{{ player.playerType.type }} </td>

                <td>
                  <button class="btn-edit btn-primary btn-xs" value="{{ player.idPlayer }}"><i class="fa fa-pencil"></i></button>
                  <button class="btn-delete btn-danger btn-xs" value="{{ player.idPlayer }}"><i class="fa fa-trash-o"></i></button>
                </td>
              </tr>
            {% endfor %}

        </table>

{% endblock %}

{% block stylesheets %}
  <!-- tables style -->
  <!-- Bootstrap core CSS -->
  <link href="{{ asset('theme/lib/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
  <!--external css-->
  <link href="{{ asset('theme/lib/font-awesome/css/font-awesome.css') }}" rel="stylesheet" />
  <!-- Custom styles for this template -->
  <link href="{{ asset('theme/css/style.css') }}" rel="stylesheet">
  <link href="{{ asset('theme/css/style-responsive.css') }}" rel="stylesheet">

  <!-- toggle style -->
  <link href="{{ asset('theme/lib/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
  <!--external css-->
  <link href="{{ asset('theme/lib/font-awesome/css/font-awesome.css') }}" rel="stylesheet" />
  <link rel="stylesheet" type="text/css" href="{{ asset('theme/lib/bootstrap-datepicker/css/datepicker.css') }}" />
  <link rel="stylesheet" type="text/css" href="{{ asset('lib/bootstrap-daterangepicker/daterangepicker.css') }}" />
  <!-- Custom styles for this template -->
  <link href="{{ asset('theme/css/style.css') }}" rel="stylesheet">
  <link href="{{ asset('theme/css/style-responsive.css') }}" rel="stylesheet">
{% endblock %}

{% block javascripts %}
  <script src="{{ asset('theme/lib/jquery/jquery.min.js') }}"></script>
  <script src="{{ asset('theme/lib/bootstrap/js/bootstrap.min.js') }}"></script>
  <script class="include" type="text/javascript" src="{{ asset('theme/lib/jquery.dcjqaccordion.2.7.js') }}"></script>
  <script src="{{ asset('theme/lib/jquery.scrollTo.min.js') }}"></script>
  <script src="{{ asset('theme/lib/jquery.nicescroll.js') }}" type="text/javascript"></script>
  <!--common script for all pages-->
  <script src="{{ asset('theme/lib/common-scripts.js') }}"></script>
  <!--script for this page-->
  <script src="{{ asset('theme/lib/jquery-ui-1.9.2.custom.min.js') }}"></script>
  <!--custom switch-->
  <script src="{{ asset('theme/lib/bootstrap-switch.js') }}"></script>
  <!--custom tagsinput-->
  <script src="{{ asset('theme/lib/jquery.tagsinput.js') }}"></script>
  <!--custom checkbox & radio-->
  <script type="text/javascript" src="{{ asset('theme/lib/bootstrap-datepicker/js/bootstrap-datepicker.js') }}"></script>
  <script type="text/javascript" src="{{ asset('theme/lib/bootstrap-daterangepicker/date.js') }}"></script>
  <script type="text/javascript" src="{{ asset('theme/lib/bootstrap-daterangepicker/daterangepicker.js') }}"></script>
  <script type="text/javascript" src="{{ asset('theme/lib/bootstrap-inputmask/bootstrap-inputmask.min.js') }}"></script>
  <script src="{{ asset('theme/lib/form-component.js') }}"></script>

  <script src="{{ asset('javascript/player.js') }}"></script>
{% endblock %}

我的控制器:

/**
 * @Route ("/", name = "player")
 */
public function players(): Response
{
    $player = $this->getDoctrine()
        ->getRepository(Player::class)
        ->findAll();

    return $this->render('manager_temp/players.html.twig', ['players' => $player]);
}

/**
 * @Route ("/table", name = "table")
 */
public function playersTable(): Response
{
    $player = $this->getDoctrine()
        ->getRepository(Player::class)
        ->findAll();

    return $this->render('manager_temp/table.html.twig', ['players' => $player]);
}

【问题讨论】:

    标签: javascript jquery symfony events toggle


    【解决方案1】:

    通过 Ajax 重新加载表格后,所有旧 DOM 元素都将被新元素替换。因此,您需要在加载新表后再次将所有事件绑定到它们。试试这个:

    $(document).ready(function() {
    
    // load the table
    $(document).on("click", ".btn-load", function() {
    
        $('.table').load('/table', function() {
            bindEvents(); //<-- Here we re-bind events
        });
        
    
    });
    
    
    function bindEvents() {
        $("input[type='checkbox']").on('change', function(){
            console.log("Hello I have changed !");
        });
    
        //toggle 
        $(document).on("change", "input", function() {
            console.log($(this).val());
            let id = $(this).val();
            let isCheck;
            if ($(this).is(":checked") === true) {
                isCheck = 1;
            } else isCheck = 0;
    
            let url = "/follow";
            let data = {'id': id, 'valeur': isCheck};
    
            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                dataType: 'html',
                cache: false
            });
    
        });
    }
    
    bindEvents(); //<-- Here we initially bind events
    
    });
    

    【讨论】:

    • 感谢您的回复。我是 jQuery 和 Ajax 的新手。我也认为问题的根源是DOM的变化。我试过这段代码,但不幸的是它不起作用。是不是当 DOM 更改时,我的切换类在 DOM 中发生了更改,因此不再调用该事件?我输入的类是 check: $ (document) .on ("change", ".check", function () {
    • @Lino,不,我的代码的问题可能是我在 $.load() 函数之后调用了 bindEvents(),而不是等待它完成。我已经编辑了我的代码,请尝试一下。
    • 我不知道它是否有帮助,但我注意到了一些东西。如果切换被复选框替换,我的事件将起作用。所以这是我的切换问题。也许它可以来自我的模板,我的div或者来自视图中js/css的实现?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多