首页 > 解决方案 > ajax加载后JavaScript不起作用(使用表)

问题描述

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

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

在这一点上一切都很好......但是......当我用表格刷新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>";

标签: javascriptjqueryajax

解决方案


您只是在页面加载时将 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 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循环从表的末尾而不是开头开始。如果您有一个包含很多行的表,那么从最后开始迭代可能会更快(因为这些是您唯一关心的行)。


推荐阅读