加载表后切换的 Jquery 事件不起作用 [英] Jquery event of toggle doesn't works after load table

查看:30
本文介绍了加载表后切换的 Jquery 事件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与 Symfony 一起开发.在我的页面上,我有一个数据表,每行都有一个切换开关.提交表单修改该表的一行后,我加载该表.但是在加载表格(不是整个页面)后,我的切换的 jQuery 事件不再起作用.我的页面在 2 个视图中分开.一个用于页面,一个用于页面上的表格.

Javascript:

$(document).ready(功能() {//加载表$(document).on("click", ".btn-load", function() {$('.table').load('/table');});$("input[type='checkbox']").on('change', function(){console.log(你好,我换了!");});//切换$(document).on("change", "input", function() {console.log($(this).val());让 id = $(this).val();让我们检查一下;if ($(this).is(":checked") === true) {isCheck = 1;否则 isCheck = 0;让 url = "/follow";让数据 = {'id': id, 'valeur': isCheck};$.ajax({类型:POST",网址:网址,数据:JSON.stringify(数据),内容类型:应用程序/json;字符集=utf-8",数据类型:'html',缓存:假});});});

页面模板:

{% 块体 %}<br><h1><center>Affichage des Players</center></h1>{% if app.user %}<li><a href="/logout">Déconnexion</a></li>{% 别的 %}<li><a href="/login">Connexion</a></li>{% 万一 %}

</节>{% endblock %}

表格模板:

{% 块表 %}<table class="table table-striped table-advance table-hover"><h4><i class="fa fa-angle-right"></i>玩家</h4><头><tr><th><i class="fa fa-home"></i>主机</th><th class="hidden-phone"><i class="fa fa-desktop"></i>目的地<th><i class="fa fa-arrows-h"></i>大的<th><i class="fa fa-arrows-v"></i>高级<th><i class="fa fa-check-circle"></i>随心所欲<th><i class="fa fa-key"></i>ID Xibo<th><i class="fa fa-info-circle"></i>类型<th><i class="fa fa-edit"></i>动作<th></th></tr></thead>{% for player in player %}<tr>//------- 这是开关 ----------{% if player.isFollowed == 1 %}<td><input class="check" id="che" type="checkbox" checked="" value="{{ player.idPlayer }}" data-toggle="switch"/></td>{% 别的 %}<td><input class="check" type="checkbox" value="{{ player.idPlayer }}" data-toggle="switch"/></td>{% 万一 %}<td>{{ player.playerType.type }} </td><td><button class="btn-edit btn-primary btn-xs" value="{{ player.idPlayer }}"><i class="fa fa-pencil"></i></按钮><button class="btn-delete btn-danger btn-xs" value="{{ player.idPlayer }}"><i class="fa fa-trash-o"></i>;/按钮></td></tr>{% 结束为 %}{% 结束块 %}{% 块样式表 %}<!-- 表格样式--><!-- Bootstrap 核心 CSS --><link href="{{ asset('theme/lib/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet"><!--外部css--><link href="{{ asset('theme/lib/font-awesome/css/font-awesome.css') }}" rel="stylesheet"/><!-- 此模板的自定义样式--><link href="{{ asset('theme/css/style.css') }}" rel="stylesheet"><link href="{{ asset('theme/css/style-responsive.css') }}" rel="stylesheet"><!-- 切换样式--><link href="{{ asset('theme/lib/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet"><!--外部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') }}"/><!-- 此模板的自定义样式--><link href="{{ asset('theme/css/style.css') }}" rel="stylesheet"><link href="{{ asset('theme/css/style-responsive.css') }}" rel="stylesheet">{% 结束块 %}{% 阻止 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><!--所有页面的通用脚本--><script src="{{ asset('theme/lib/common-scripts.js') }}"></script><!--此页面的脚本--><script src="{{ asset('theme/lib/jquery-ui-1.9.2.custom.min.js') }}"></script><!--自定义开关--><script src="{{ asset('theme/lib/bootstrap-switch.js') }}"></script><!--自定义标签输入--><script src="{{ asset('theme/lib/jquery.tagsinput.js') }}"></script><!--自定义复选框&无线电--><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")*/公共功能玩家():响应{$player = $this->getDoctrine()->getRepository(Player::class)->findAll();return $this->render('manager_temp/players.html.twig', ['players' => $player]);}/*** @Route ("/table", name = "table")*/公共函数playersTable():响应{$player = $this->getDoctrine()->getRepository(Player::class)->findAll();return $this->render('manager_temp/table.html.twig', ['players' => $player]);}

解决方案

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

$(document).ready(function() {//加载表$(document).on("click", ".btn-load", function() {$('.table').load('/table', function() {绑定事件();//<-- 这里我们重新绑定事件});});函数绑定事件(){$("input[type='checkbox']").on('change', function(){console.log(你好,我换了!");});//切换$(document).on("change", "input", function() {console.log($(this).val());让 id = $(this).val();让我们检查一下;if ($(this).is(":checked") === true) {isCheck = 1;否则 isCheck = 0;让 url = "/follow";让数据 = {'id': id, 'valeur': isCheck};$.ajax({类型:POST",网址:网址,数据:JSON.stringify(数据),内容类型:应用程序/json;字符集=utf-8",数据类型:'html',缓存:假});});}绑定事件();//<-- 这里我们最初绑定事件});

I am developing with Symfony. On my page I have a data table with a toggle for each row. After submitting a form to modify a row of this table, I load the table. However after loading the table (not the whole page), my toggle's jQuery event no longer works. My page is separated in 2 view. One for the page and one for the table on the page.

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
        });

    });


});

Page template :

{% 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 %}

table template :

{% 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 %}

my controller :

/**
 * @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]);
}

解决方案

After reloading table via Ajax all old DOM elements are being replaced with new ones. So, you need to bind all events to them again, after loading new table. Try this:

$(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 事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆