繁体   English   中英

ajax 加载后 JavaScript 不起作用(使用表)

[英]JavaScript doesn't work after ajax loading (using table)

我有一个由数据库使用 php 自动生成的四行表...最后一行 (4) 有一个按钮来触发下面的 function ...它对每一行重复。

单击按钮后...脚本发送更新数据库的请求以将状态“挂起”切换为“已取消”。

在这一点上一切都很好......但是......当我用表格刷新div时“$('#lista').load(location.href +'#lista> *');”

该脚本在加载后第二次不起作用。 ( div 更新没问题,但只能工作一次)

第一次刷新后我需要脚本工作......每次我点击行按钮......

我认为这可能是 ajax 请求和 javascript 不兼容。

如果你能帮助我,我真的很感激。 谢谢你们。

<script>

var index, table = document.getElementById('table');
            for(var i = 1; i < table.rows.length; i++)
            {
                table.rows[i].cells[4].onclick = function()
                { //inicio da função
                    var c = confirm('Você quer cancelar essa aula?');
                    if(c === true)
                    {//inicio confirmador
                      var table = document.getElementById('table');
                        index = this.parentElement.rowIndex;
                        value_index_id= table.rows[index].cells[0].innerHTML;
                        var id = value_index_id;
                        $.ajax({
                  type: 'GET',
                  url: 'cancelar_aulas.php',
                  data: {id_geral:id},
                  success: function(data){
                    alert(data);
                    $( '#lista' ).load(location.href + ' #lista > *' );

                  }
              })

                    } //fim do confirmador

                    //validador
                    //console.log(index);
                    //console.log (value_index_id);
                    console.log(id);

                };//fim da função

            }
</script>";

您只是在页面加载时将 onclick 事件处理程序附加到表中。 这就是为什么它只适用于第一次点击。 当您向表中添加新数据时,您需要将 onclick 事件添加到新行中。

有几种不同的方法可以做到这一点:

  • jQuery 可以将事件附加到动态创建的元素,如下所示:

     $("table").on("click", "table tr", function() { // Note that this event would fire for ALL rows, // but it will automatically attach this event to new rows // that are added after page load // This would work, you just would have to check if the clicked // row is one of the last 4. }
  • 创建您自己的 function 以附加该事件,并且您将在每次添加新行时运行该 function。 就像是:

     function AttachClick() { let table = document.getElementById("table"); let position = table.rows.length; while (position > table.rows.length - 4) { table.rows[position].addEventListener("click", function() { // Do your on click here // On success, you would fire this "AttachClick()" function } position--; } }

注意while循环从表的末尾而不是开头开始。 如果您有一个包含很多行的表,那么从最后开始迭代可能会更快(因为这些是您唯一关心的行)。

暂无
暂无

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

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